Module:ArgsLib

From The Remnant 2 Wiki
Jump to navigation Jump to search

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

local m_type = require('Module:TypesLib')
local lib = {}

-- Casts an individual parameter into its lua type
function lib.castParam(v, t)
	if not v or v == '' then return nil end
	if not t then return v end

	if t == 'string' then
		return v
	elseif t == 'boolean' then
		return m_type.to_bool(v)
	elseif t == 'number' or t == 'integer' or t == 'float' then
		return tonumber(v)
	elseif t == 'namespace' then
		return mw.site.namespaces[tonumber(v)].name
	end

	error('Unrecognized type: ' .. t)
end

-- Cast args into configuration provided by params
-- Params format:
--  {
--    param_name = {
--      required = true, -- optional
--      type = 'string', -- lua type
--    },
--    .. continued for all params
--  }
function lib.cast(args, params)
	for k, param in pairs(params) do
		args[k] = lib.castParam(args[k], param.type)
		if not args[k] then
			if param.required then error('Missing required param: ' .. k) end
			if param.default then args[k] = param.default end
		end
	end
end

-- Merge module and template args
-- Template args overwrite matching module args
function lib.merge()
	local args = {}
	local fr = mw.getCurrentFrame()
	
	local m_args = fr.args
	for k, v in pairs(m_args) do
		v = mw.text.trim(tostring(v))
		if v ~= '' then
			args[k] = v
		end
	end
	
	local t_args = fr:getParent().args
	for k, v in pairs(t_args) do
		v = mw.text.trim(v)
		if v ~= '' then
			args[k] = v
		end
	end
	
	return args
end

-- Merges numbered args to table
-- e.g. |param = value |param2 = value2 --> [value, value2]
-- Accepts both param1 or param as the first index
-- @args frame args, template args, or merged args
-- @name base parameter name
-- @count expected number of args
function lib.merge_numbered_args(args, name, count)
    local tbl = {}
    local i = 1
    count = count or -1

    local arg = args[name] or args[name .. i]
    while count < 0 and arg or i <= count do
        tbl[i] = arg
		i = i + 1
        arg = args[name .. i]
    end
    
    return next(tbl) and tbl or nil
end

return lib