跳转到内容

模块:Pn

本页使用了标题或全文手工转换
维基百科,自由的百科全书
文档图示 模块文档[查看] [编辑] [历史] [清除缓存]

The module returns one value from its list of unnamed parameters.

The named parameter |idx= is the index of the parameter that is to be returned.

Negative indices count backward from the end of the list.

A wrapper template may be used to simplify usage.

Examples

[编辑]
  • {{#invoke:Pn |getVal | idx=1}}
  • {{#invoke:Pn |getVal | idx= | a | b | c | d | e | f }} → a
  • {{#invoke:Pn |getVal | idx=0 | a | b | c | d | e | f }}
  • {{#invoke:Pn |getVal | idx=1 | a | b | c | d | e | f }} → a
  • {{#invoke:Pn |getVal | idx=2 | a | b | c | d | e | f }} → b
  • {{#invoke:Pn |getVal | idx=-1 | a | b | c | d | e | f }} → f
  • {{#invoke:Pn |getVal | idx=99 | a | b | c | d | e | f }}

Using a wrapper template, {{P-1}}:

  • {{p-1 | a | b | c | d | e | f }} → f
  • {{wdib|ps=1|P8011|qid=Q84055514}}
  • {{wdib|ps=1|P8011|qid=Q84055514|list=p-1}}

--[[
Module that returns one value from a list of unnamed parameters
Named parameter idx is the index of the parameter that is to be returned
Negative indices count backward from the end of the list
==]]

local p = {}

p.getVal = function(frame)
	local args = {}
	-- copy arguments from frame object and its parent
	local has_num_arg = false
	if type(frame.args) == type({}) then
        -- We're being called via #invoke. The args are passed through to the module
        -- from the template page, so use the args that were passed into the template.
		for k, v in pairs(frame.args) do
			has_num_arg = has_num_arg or (not not tonumber(k))
			args[k] = v
		end
		for k, v in pairs(frame:getParent().args) do
			has_num_arg = has_num_arg or (not not tonumber(k))
			args[k] = v
		end
	elseif type(frame) == type({}) then
        -- We're being called from another module or from the debug console, so assume
        -- the args are passed in directly.
		for k, v in pairs(frame) do
			has_num_arg = has_num_arg or (not not tonumber(k))
			args[k] = v
		end
	end
	if not args[1] and not has_num_arg then
		return nil
	end
	local idx = tonumber(args.idx) or 1
	if idx < 0 then 
		local _max = 0
		for k, v in pairs(args) do
			local id = tonumber(k)
			if id and id > _max then _max = id end
		end
		idx = _max + idx + 1 
	end
	return args[idx]
end

return p