Module:Arguments

From Puella Magi Wiki
Jump to navigation Jump to search

This is a utility module that lets you use arguments from either the current frame (i.e., {{#invoke:...}}) or the parent frame (i.e., {{Template:...}}) without having to care which frame is the correct one. Using getArgs also lets you call a module from another module without passing a frame (i.e., by passing arguments normally).

Usage

local getArgs = require('Module:Arguments').getArgs
local p = {}

function p.main(...)
	local args = getArgs(...)
	-- Main module code goes here.
end

return p

local p = {}

function p.getArgs(frame, ...)
	local args = {}
	
	-- Fun:	getArgs("foo", "bar", "baz")
	-- Ret:	{"foo", "bar", "baz"}
	if select('#', ...) > 0 then
		local varargs = {...}
		args[1] = frame
		for i, v in ipairs(varargs) do
			args[i + 1] = v
		end

	-- Fun:	getArgs(mw.getCurrentFrame():newChild{
	--			title="Module:Arguments",
	--			args={"foo", "bar", "baz"}
	--		})
	-- Ret:	{"foo", "bar", "baz"}
	elseif type(frame) == 'table' and frame.args then
		for k, v in pairs(frame.args) do
			v = mw.text.trim(tostring(v))
			args[k] = v
		end
		
		local parent = frame:getParent()
		if parent then
			for k, v in pairs(parent.args) do
				v = mw.text.trim(v)
				args[k] = v
			end
		end

	-- Fun:	getArgs("foo")
	-- Ret:	{"foo"}
	elseif type(frame) ~= 'table' then
		args = {frame}

	-- Fun:	getArgs({"foo"})
	-- Ret:	{"foo"}
	elseif frame then
		args = frame
	end

	return args
end

return p