Module:GetString

From Dead Cells Wiki
Jump to navigation Jump to search

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

local p = {}
local h = {}

-- Given an array with gaps, returns a new sequence with all gaps removed.
-- For example, `{nil, 2, nil, 4, 5, 6, nil, 8}` will become `{2, 4, 5, 6, 8}`.
function h.removeGaps(args)
   local argPairs = {}
   local argIndex = 1
   for index, arg in pairs(args) do
      if type(index) == "number" then
         argPairs[argIndex] = {index, arg}
         argIndex = argIndex + 1
      end
   end
   
   table.sort(argPairs, function(a, b) return a[1] < b[1] end)
   
   local sortedArgs = {}
   for index, argPair in ipairs(argPairs) do
      local arg = argPair[2]
      sortedArgs[index] = arg
   end
   
   return sortedArgs
end

function p._process(args)
   local args = h.removeGaps(args)

   -- Find the first arg not starting with `prev`
   local firstNonPrev = 0
   for index, arg in ipairs(args) do
   	  firstNonPrev = index
   	  if not string.match(arg, "^prev") then
   	     break
   	  end
   end
   
   -- Get a table of all args from the first non-prev one down to 1 and strip the `prev` prefixes
   local textParts = {}
   for part = firstNonPrev, 1, -1 do
   	  textParts[firstNonPrev - part + 1] = string.gsub(args[part], "^prev", "")
   end
   
   return table.concat(textParts, ", ")
end

function p.process(frame)
   local args = require("Module:Arguments").getArgs(frame)
   return p._process(args)
end
 
return p