Module:Xswitch

From Omniversalis

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

p = {}

function extractprofile(profile, type)
 -- takes a profile like [[Templates:xswitch/test-profile]] and extracts the levels and results, _instead_ of having them passed as parameters

   local x = 0
   local pattern = {}
   local mins = {}
   local results = {}
   for min,result in mw.ustring.gmatch(profile, "(.-)|(.-)\n") do
      if min then
         if type then
         	min = tostring(min)
         else
         	min = tonumber(min)
         end -- and I have nofklu WHAT this does to Unicode, sorry!  Tostring is supposedly not necessary but I am suspicious.
         table.insert(mins, min)
         table.insert(results, (result or ""))
      end
   end
   return mins,results
end

function p.main(frame)
   local args = frame.args
   local parent, pargs, type, profile, input, number
   if frame.getparent then 
       parent = frame:getparent()
       pargs = parent.args
       type = pargs.type
       input = pargs[1]
   end -- I have nofklu why this gives me an error this time.  Say who what?
   type = type or args.type or nil -- sort as number or string.  Default to number (nil), think.
   profile = profile or args.profile or nil -- File to transclude to obtain the thresholds
   input = input or args[1] or ""
   if type then input = tostring(input) else input = tonumber(input) end
   local mins = {}
   local results = {}
   if profile then
   	  mins,results = extractprofile(profile, type)
   	  number=table.maxn(mins)
   end
   if not(mins[1]) then -- (no profile or profile extraction unsuccessful)
      mins={}; results={} -- suspicious mind...
      number = 0
      repeat
         number = number + 1
         local min
         if parent then min = pargs[number * 2]; result = pargs[number * 2 + 1] else min = nil; result = nil end
         min = min or args[number * 2] or nil -- numbered params from 2 on alternate as threshold and result
         local result = result or args[number*2+1] or ""
         if min then
            if type then
            	min = tostring(min)
            else
            	min = tonumber(min)
            end
            table.insert(mins, min)
            table.insert(results, (result or ""))
         end
      until not(mins[number])
   end
   local toolow = results[number - 1] or ""
   while number > 1 do
      number = number-1
      if input > mins[number] then
      	output = results[number];
      	break
      end
   end

   return (output or toolow or "")

end

return p