Module: Iterate

From A Wiki of Ice and Fire
Jump to: navigation, search

This module takes in as only argument a string containing numbers separated by ; and - and returns a Lua table with all the values represented by that string.

Example

1-3;5;9-12 will give a table containing: 1, 2, 3, 5, 9, 10, 11, 12.


local p = {}

function p._split(str, sep)
        if sep == nil then
                sep = "%s"
        end
        local t={} ; i=1
        for str in mw.ustring.gmatch(str, "([^"..sep.."]+)") do
                t[i] = str
                i = i + 1
        end
        return t
end

function p._iterate(arg)
	local numbers = {}
	local ranges = p._split(arg, ';')
	for _,v in pairs(ranges) do
		if mw.ustring.find(v, "^%d+%-%d+$") then
			local s = mw.ustring.match(v, "^%d+")
			local e = mw.ustring.match(v, "%d+$")
			for i=tonumber(s),tonumber(e) do
				table.insert(numbers,i)
			end
		elseif mw.ustring.find(v, "^%d+$") then
			table.insert(numbers, tonumber(mw.ustring.match(v, "^%d+$")))
		end
	end
	return numbers
end

function p.iterate(arg)
	return p._iterate(arg)
end

function p.main(frame)
	local args = frame.args
    if args[1] == nil then
        args = frame:getParent().args
    end
    if args[1] == nil then
    	return ""
    end
    return p._iterate(args[1])
end

return p