Module:ArrayParameter

From Puella Magi Wiki
Jump to navigation Jump to search

This module enables a template to handle multiple "array-like" parameters. It defines an "array-like" as any set of parameters that consist of a common prefix followed by a number. The numbers must be sequential, or the module will raise an error.

The module takes every matching parameter, substitutes its value into a template, and concatenates the result together.

Usage: {{#invoke|ArrayParameter|main|name=...|...}}

The following parameters are supported:

  • name – The name of the array-like parameter. If name=char, then the module looks for template parameters called char_n where n is any positive integer. Defaults to arg if not specified.
  • separator – A string used as a separator when concatenating. Defaults to an empty string if not specified.
  • first, last – If specified, the transformation is limited to the subsequence of parameters with the indicated indices. A negative index counts from the end. For example, if you pass name=value, first=3, and last=-2, and there are 10 parameters passed to the template, then only the parameters from value_3 to value_9 are formatted and concatenated.
  • template or unnamed parameter – The template to substitute the values into. The string %s will be replaced with the values of the parameters.

local p = {}

function p.main(frame)
	local arg_name = frame.args.name or ''
	local template = frame.args.template or frame.args[1] or ''
	local sep = frame.args.separator or ''
	local parent_frame = frame:getParent()
	local result = {}
	local first = true
	for arg, val in pairs(parent_frame.args) do
		local m
		if arg_name == '' then
			m = arg:match('^(%d+)$')
		else
			m = arg:match('^' .. arg_name .. '_(%d+)$')
		end
		if m then
			local i = tonumber(m)
			result[i] = template:gsub('%%s', val)
		end
	end
	local first, last = frame.first or 1, frame.last or -1
	local size = table.maxn(result)
	if first < 0 then first = first + size + 1 end
	if last < 0 then last = last + size + 1 end
	if first == last then return result[first] end
	if first > last then first,last = last,first end
	return table.concat(result, sep, first, last)
end

return p