From WikiChip
Module:wikichip
Revision as of 23:13, 25 May 2017 by ChipIt (talk | contribs)

Documentation for this module may be created at Module:wikichip/doc

local wikichip = {}
local chip = {
  result = nil,
  valid = false
}

function wikichip:new(name)
	chip.result = mw.smw.getQueryResult(
    	'[[name::' .. name .. ']][[instance of::microprocessor]]' ..
    	'|?full page name' ..
    	'|?name' ..
    	'|?designer' ..
    	'|limit=1|mainlabel=page'
    )
    
    return chip
end

function chip.is_valid()
  if not chip.result.results[1] then
    return false
  end
  return true
end

function chip.attr(attr)
  return chip.result.results[1].printouts[attr]
end

function chip.designer()	return chip.attr('designer')[1]		end
function chip.name()		return chip.attr('name')[1]			end


-- Because key,value pairs are stored arbitrarily in the tables, this
-- function sorts the keys and returns the key,value pairs in sorted order.
function sortedPairs(unsortedTable)
  -- Get all the keys from the table
  local keys = {}
  for key in pairs(unsortedTable) do
    keys[#keys+1] = key
  end
  
  -- Sort'em!
  table.sort(keys)
  
  local i = 0
  return function()
    i = i + 1
    if keys[i] then
      return keys[i], unsortedTable[keys[i]]
    end
  end
end

function print(s)
  mw.log(s)	
end

function wikichip.print_r ( t )  
    local print_r_cache={}
    local function sub_print_r(t,indent)
        if (print_r_cache[tostring(t)]) then
            print(indent.."*"..tostring(t))
        else
            print_r_cache[tostring(t)]=true
            if (type(t)=="table") then
                for pos,val in pairs(t) do
                    if (type(val)=="table") then
                        print(indent.."["..pos.."] => "..tostring(t).." {")
                        sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
                        print(indent..string.rep(" ",string.len(pos)+6).."}")
                    elseif (type(val)=="string") then
                        print(indent.."["..pos..'] => "'..val..'"')
                    else
                        print(indent.."["..pos.."] => "..tostring(val))
                    end
                end
            else
                print(indent..tostring(t))
            end
        end
    end
    if (type(t)=="table") then
        print(tostring(t).." {")
        sub_print_r(t,"  ")
        print("}")
    else
        sub_print_r(t,"  ")
    end
    print()
end

return wikichip