Module:参数
![]() | 此页面在多个 wiki 之间共享。 对此页面的所有更改都将自动复制到左侧栏中列出的所有 wiki。 为避免不必要的页面重新生成和服务器加载,应在页面的沙盒上测试更改。 请帮忙翻译这个页面。 |
![]() | 此模块用于系统消息。 对它的更改可能会导致 MediaWiki 用户界面立即发生变化。为避免大规模中断,任何更改都应该首先在此模块的 /sandbox 或 /testcases 子页面中或在您自己的用户空间中进行测试。然后,可以在一次编辑中将测试的更改添加到此模块中。在实施之前,请在讨论页上讨论任何更改。 |
![]() | 此模块被评为一般就绪型。它已经达到了成熟的形式,被认为没有错误,可以在适当的地方使用。它已准备好在帮助页面和其他资源中提及,作为新用户学习的选项。为了减少服务器负载和不良输出,应该通过沙盒测试来改进它,而不是重复的试错编辑。 |
![]() | 此模块受级联保护。它是一个高度可见的模块,被大量页面使用。因为故意破坏或错误会影响许多页面,即使是微不足道的编辑也可能给服务器带来巨大的负载,所以它受到保护,不会被编辑。 |
此模块可以轻松处理从 {{#invoke:...}}
传递的参数。它是一个元模块,供其他模块使用,不应直接从 {{#invoke:...}}
调用。其功能包括:
轻松修剪参数并删除空白参数。
当前帧和父帧可以同时传递参数。(更多详情见下文。
参数可以直接从另一个 Lua 模块或调试控制台传入。
根据需要获取参数,这有助于避免<ref>
标签的(一些)问题。
大多数功能都可以自定义。
基本用途
首先,您需要加载模块。它包含一个名为 getArgs
的函数。
local getArgs = require('Module:Arguments').getArgs
在最基本的情况下,您可以在 main 函数中使用 getArgs
。变量 args
是一个包含 {{#invoke:...}}
参数的表。(有关详细信息,请参阅下文。
local getArgs = require('Module:Arguments').getArgs
local p = {}
function p.main(frame)
local args = getArgs(frame)
-- Main module code goes here.
end
return p
但是,推荐的做法是使用函数来处理来自 {{#invoke:...}}
的参数。这意味着,如果有人从另一个 Lua 模块调用你的模块,你不必有可用的 frame 对象,从而提高性能。
local getArgs = require('Module:Arguments').getArgs
local p = {}
function p.main(frame)
local args = getArgs(frame)
return p._main(args)
end
function p._main(args)
-- Main module code goes here.
end
return p
如果您希望多个函数使用参数,并且还希望它们可以从 {{#invoke:...}}
访问,则可以使用包装函数。
local getArgs = require('Module:Arguments').getArgs
local p = {}
local function makeInvokeFunc(funcName)
return function (frame)
local args = getArgs(frame)
return p[funcName](args)
end
end
p.func1 = makeInvokeFunc('_func1')
function p._func1(args)
-- Code for the first function goes here.
end
p.func2 = makeInvokeFunc('_func2')
function p._func2(args)
-- Code for the second function goes here.
end
return p
选项
以下选项可用。它们将在以下各节中解释。
local args = getArgs(frame, {
trim = false,
removeBlanks = false,
valueFunc = function (key, value)
-- Code for processing one argument
end,
frameOnly = true,
parentOnly = true,
parentFirst = true,
wrappers = {
'Template:A wrapper template',
'Template:Another wrapper template'
},
readOnly = true,
noOverwrite = true
})
修剪和删除空白
空白参数经常让刚开始将 MediaWiki 模板转换为 Lua 的程序员感到困惑。在模板语法中,空白字符串和仅包含空格的字符串被视为 false
。但是,在 Lua 中,空白字符串和由空格组成的字符串被视为 true
。这意味着,如果你在编写 Lua 模块时不注意这些参数,你可能会把一些东西看作是 true
,而实际上应该把它看作是 false
。为避免这种情况,默认情况下,此 module 会删除所有空白参数。
同样,在处理位置参数时,空格也会导致问题。尽管对于来自 {{#invoke:...}}
的命名参数,它被修剪,但它被保留用于位置参数。大多数时候,这个额外的空格是不需要的,所以这个模块默认会把它修剪掉。
但是,有时您希望使用空白参数作为输入,有时您希望保留额外的空格。这对于完全按照编写的方式转换某些模板是必要的。如果要执行此作,可以将 trim
和 removeBlanks
参数设置为 false
。
local args = getArgs(frame, {
trim = false,
removeBlanks = false
})
参数的自定义格式
有时你想删除一些空白参数,但不删除其他参数,或者你可能想把所有位置参数都放在小写。要执行此类作,您可以使用 valueFunc
选项。此选项的输入必须是一个函数,该函数采用两个参数(key
和 value
)并返回单个值。此值是您在访问 args
表中的字段键
时将获得的值。
示例 1:
此函数保留第一个位置参数的空格,但会剪裁所有其他参数并删除所有其他空白参数。
local args = getArgs(frame, {
valueFunc = function (key, value)
if key == 1 then
return value
elseif value then
value = mw.text.trim(value)
if value ~= '' then
return value
end
end
return nil
end
})
示例 2:
此函数删除空白参数并将所有参数转换为小写,但不会从位置参数中修剪空格。
local args = getArgs(frame, {
valueFunc = function (key, value)
if not value then
return nil
end
value = mw.ustring.lower(value)
if mw.ustring.find(value, '%S') then
return value
end
return nil
end
})
如果传递的输入不是
string
或 nil
类型,则上述函数将失败。
如果您在模块的 main 函数中使用 getArgs
函数,并且该函数由另一个 Lua 模块调用,则可能会出现这种情况。在这种情况下,您需要检查输入的类型。
如果你正在使用专门用于
{{#invoke:...}}
参数的函数(例如,你有 p.main
和 p._main
函数,或类似函数),这不是问题。示例 1 和 2 进行类型检查 |
---|
另外,请注意,每次从 args
表中请求参数时,或多或少都会调用 valueFunc
函数,因此,如果您关心性能,则应确保没有对代码执行任何低效作。
帧和父帧
args
表中的参数可以同时从当前帧或父帧传递。要理解这意味着什么,最简单的举个例子。假设我们有一个名为 Module:ExampleArgs
的模块。此模块打印它所传递的前两个位置参数。
Module:ExampleArgs 代码 |
---|
然后,Template
:ExampleArgs 由 Template:ExampleArgs
调用,其中包含代码 {{#invoke:ExampleArgs|main|firstInvokeArg}}
。这将生成结果 “firstInvokeArg”。
现在,如果我们调用 Template:ExampleArgs
,将发生以下情况:
法典 | Result |
---|---|
{{ExampleArgs}}
|
firstInvokeArg |
{{ExampleArgs|firstTemplateArg}}
|
firstInvokeArg |
{{ExampleArgs|firstTemplateArg|secondTemplateArg}}
|
firstInvokeArg secondTemplateArg |
您可以设置三个选项来更改此行为:frameOnly
、parentOnly
和 parentFirst
。如果设置 frameOnly
,则仅接受从当前帧传递的参数;如果设置 parentOnly
,则仅接受从父框架传递的参数;如果你设置了 parentFirst
,那么参数将从当前帧和父帧传递,但父帧将优先于当前帧。以下是 Template:ExampleArgs
的结果:
仅帧
-
法典 Result {{ExampleArgs}}
firstInvokeArg {{ExampleArgs|firstTemplateArg}}
firstInvokeArg {{ExampleArgs|firstTemplateArg|secondTemplateArg}}
firstInvokeArg 仅父
-
法典 Result {{ExampleArgs}}
{{ExampleArgs|firstTemplateArg}}
firstTemplateArg {{ExampleArgs|firstTemplateArg|secondTemplateArg}}
firstTemplateArg secondTemplateArg parentFirst (父优先)
-
法典 Result {{ExampleArgs}}
firstInvokeArg {{ExampleArgs|firstTemplateArg}}
firstTemplateArg {{ExampleArgs|firstTemplateArg|secondTemplateArg}}
firstTemplateArg secondTemplateArg
如果你同时设置了 frameOnly
和parentOnly
选项,模块根本不会从{{#invoke:...}}
获取任何参数。这可能不是您想要的。
在某些情况下,父帧可能不可用,例如,如果getArgs
传递父帧而不是当前帧。在这种情况下,将仅使用 frame 参数(除非设置了 parentOnly
,在这种情况下,将不使用任何参数),并且parentFirst
和frameOnly
选项将不起作用。
包装
wrappers
选项用于指定有限数量的模板作为包装器模板,即,其唯一目的是调用模块的模板。如果模块检测到它正在从包装器模板调用,则它只会检查父框架中的参数;否则,它只会检查传递给 getArgs
的帧中的参数。这允许 {{#invoke:...}}
或通过包装模板调用模块,而不会因必须检查每个参数查找的帧和父帧而造成性能损失。
例如,{{Navbox}} 的唯一内容(不包括 <noinclude>...</noinclude>
标签)是{{#invoke:Navbox|navbox}}
。检查直接传递给此模板的 {{#invoke:...}}
语句的参数是没有意义的,因为那里永远不会指定任何参数。我们可以通过使用 parentOnly
选项来避免检查传递给 {{#invoke:...}}
的参数,但如果我们这样做,那么 {{#invoke:...}}
在其他页面上也不起作用。如果是这种情况,那么 |text=
代码 {{#invoke:Navbox|navbox|text=Some text}}
中的一些文本将被完全忽略,无论它是从哪个页面使用的。通过使用 wrappers
选项指定 Template:Navbox 作为包装器,我们可以在大多数页面上工作 {{#invoke:Navbox|main|text=Some text}}
,同时仍然不需要模块检查 Template:Navbox 页面本身的参数。
包装器可以指定为字符串或字符串数组。
local args = getArgs(frame, {
wrappers = 'Template:Wrapper template'
})
local args = getArgs(frame, {
wrappers = {
'Template:Wrapper 1',
'Template:Wrapper 2',
-- Any number of wrapper templates can be added here.
}
})
该模块将自动检测它是否是从包装器模板的/sandbox
子页面调用的,因此无需显式指定沙盒页面。wrappers
选项有效地更改了frameOnly
和parentOnly
选项的默认值。例如,如果在设置了包装器
的情况下将parentOnly
显式设置为false
,则通过包装器模板进行的调用将导致同时加载 frame 和 parent 参数,尽管不通过包装器模板进行的调用将导致仅加载 frame 参数。
如果设置了wrappers
选项并且没有可用的父框架,则模块将始终从传递给getArgs
的框架中获取参数。
写入 args
表
有时,将新值写入 args
表可能很有用。这可以通过此模块的默认设置来实现。(但是,请记住,使用新值创建新表并根据需要从 args
表中复制参数通常是更好的编码样式。
args.foo = 'some value'
可以使用 readOnly
和 noOverwrite
选项更改此行为。如果设置了 readOnly
,则根本无法将任何值写入 args
表。如果设置了 noOverwrite
,则可以向表中添加新值,但如果该值会覆盖从 {{#invoke:...}}
传递的任何参数,则无法添加值。
Ref 标签
此模块使用元表从 {{#invoke:...}}
获取参数。这允许在不使用 pairs()
函数的情况下访问 frame 参数和 parent frame 参数。如果您的模块可能被作为输入传递 <ref>
标签,这会有所帮助。
一旦从 Lua 访问 <ref>
标签,它们就会被 MediaWiki 软件处理,并且引用将出现在文章底部的引用列表中。如果您的模块继续从输出中省略 reference 标签,您最终将得到一个幻像引用 - 一个出现在引用列表中的引用,但没有链接到它的编号。对于使用 pairs()
来检测是使用框架还是父框架中的参数的模块来说,这是一个问题,因为这些模块会自动处理每个可用的参数。
该模块通过允许访问 frame 和 parent frame 参数来解决此问题,同时仍然仅在必要时获取这些参数。但是,如果您在模块中的其他位置使用 pairs(args),
问题仍然会出现。
已知限制
使用 metatables 也有其缺点。大多数普通的 Lua 表工具在 args
表上无法正常工作,包括 #
运算符、next()
函数和表
库中的函数。如果使用它们对您的模块很重要,您应该使用自己的参数处理函数而不是此模块。
测试
Module:参数 | 成功:51,错误:0,跳过:0 |
Module:Arguments/sandbox | 成功:51,错误:0,跳过:0 |
-- This module provides easy processing of arguments passed to Scribunto from
-- #invoke. It is intended for use by other Lua modules, and should not be
-- called from #invoke directly.
local libraryUtil = require('libraryUtil')
local checkType = libraryUtil.checkType
local arguments = {}
-- Generate four different tidyVal functions, so that we don't have to check the
-- options every time we call it.
local function tidyValDefault(key, val)
if type(val) == 'string' then
val = val:match('^%s*(.-)%s*$')
if val == '' then
return nil
else
return val
end
else
return val
end
end
local function tidyValTrimOnly(key, val)
if type(val) == 'string' then
return val:match('^%s*(.-)%s*$')
else
return val
end
end
local function tidyValRemoveBlanksOnly(key, val)
if type(val) == 'string' then
if val:find('%S') then
return val
else
return nil
end
else
return val
end
end
local function tidyValNoChange(key, val)
return val
end
local function matchesTitle(given, title)
local tp = type( given )
return (tp == 'string' or tp == 'number') and mw.title.new( given ).prefixedText == title
end
local translate_mt = { __index = function(t, k) return k end }
function arguments.getArgs(frame, options)
checkType('getArgs', 1, frame, 'table', true)
checkType('getArgs', 2, options, 'table', true)
frame = frame or {}
options = options or {}
--[[
-- Set up argument translation.
--]]
options.translate = options.translate or {}
if getmetatable(options.translate) == nil then
setmetatable(options.translate, translate_mt)
end
if options.backtranslate == nil then
options.backtranslate = {}
for k,v in pairs(options.translate) do
options.backtranslate[v] = k
end
end
if options.backtranslate and getmetatable(options.backtranslate) == nil then
setmetatable(options.backtranslate, {
__index = function(t, k)
if options.translate[k] ~= k then
return nil
else
return k
end
end
})
end
--[[
-- Get the argument tables. If we were passed a valid frame object, get the
-- frame arguments (fargs) and the parent frame arguments (pargs), depending
-- on the options set and on the parent frame's availability. If we weren't
-- passed a valid frame object, we are being called from another Lua module
-- or from the debug console, so assume that we were passed a table of args
-- directly, and assign it to a new variable (luaArgs).
--]]
local fargs, pargs, luaArgs
if type(frame.args) == 'table' and type(frame.getParent) == 'function' then
if options.wrappers then
--[[
-- The wrappers option makes Module:Arguments look up arguments in
-- either the frame argument table or the parent argument table, but
-- not both. This means that users can use either the #invoke syntax
-- or a wrapper template without the loss of performance associated
-- with looking arguments up in both the frame and the parent frame.
-- Module:Arguments will look up arguments in the parent frame
-- if it finds the parent frame's title in options.wrapper;
-- otherwise it will look up arguments in the frame object passed
-- to getArgs.
--]]
local parent = frame:getParent()
if not parent then
fargs = frame.args
else
local title = parent:getTitle():gsub('/sandbox$', '')
local found = false
if matchesTitle(options.wrappers, title) then
found = true
elseif type(options.wrappers) == 'table' then
for _,v in pairs(options.wrappers) do
if matchesTitle(v, title) then
found = true
break
end
end
end
-- We test for false specifically here so that nil (the default) acts like true.
if found or options.frameOnly == false then
pargs = parent.args
end
if not found or options.parentOnly == false then
fargs = frame.args
end
end
else
-- options.wrapper isn't set, so check the other options.
if not options.parentOnly then
fargs = frame.args
end
if not options.frameOnly then
local parent = frame:getParent()
pargs = parent and parent.args or nil
end
end
if options.parentFirst then
fargs, pargs = pargs, fargs
end
else
luaArgs = frame
end
-- Set the order of precedence of the argument tables. If the variables are
-- nil, nothing will be added to the table, which is how we avoid clashes
-- between the frame/parent args and the Lua args.
local argTables = {fargs}
argTables[#argTables + 1] = pargs
argTables[#argTables + 1] = luaArgs
--[[
-- Generate the tidyVal function. If it has been specified by the user, we
-- use that; if not, we choose one of four functions depending on the
-- options chosen. This is so that we don't have to call the options table
-- every time the function is called.
--]]
local tidyVal = options.valueFunc
if tidyVal then
if type(tidyVal) ~= 'function' then
error(
"bad value assigned to option 'valueFunc'"
.. '(function expected, got '
.. type(tidyVal)
.. ')',
2
)
end
elseif options.trim ~= false then
if options.removeBlanks ~= false then
tidyVal = tidyValDefault
else
tidyVal = tidyValTrimOnly
end
else
if options.removeBlanks ~= false then
tidyVal = tidyValRemoveBlanksOnly
else
tidyVal = tidyValNoChange
end
end
--[[
-- Set up the args, metaArgs and nilArgs tables. args will be the one
-- accessed from functions, and metaArgs will hold the actual arguments. Nil
-- arguments are memoized in nilArgs, and the metatable connects all of them
-- together.
--]]
local args, metaArgs, nilArgs, metatable = {}, {}, {}, {}
setmetatable(args, metatable)
local function mergeArgs(tables)
--[[
-- Accepts multiple tables as input and merges their keys and values
-- into one table. If a value is already present it is not overwritten;
-- tables listed earlier have precedence. We are also memoizing nil
-- values, which can be overwritten if they are 's' (soft).
--]]
for _, t in ipairs(tables) do
for key, val in pairs(t) do
if metaArgs[key] == nil and nilArgs[key] ~= 'h' then
local tidiedVal = tidyVal(key, val)
if tidiedVal == nil then
nilArgs[key] = 's'
else
metaArgs[key] = tidiedVal
end
end
end
end
end
--[[
-- Define metatable behaviour. Arguments are memoized in the metaArgs table,
-- and are only fetched from the argument tables once. Fetching arguments
-- from the argument tables is the most resource-intensive step in this
-- module, so we try and avoid it where possible. For this reason, nil
-- arguments are also memoized, in the nilArgs table. Also, we keep a record
-- in the metatable of when pairs and ipairs have been called, so we do not
-- run pairs and ipairs on the argument tables more than once. We also do
-- not run ipairs on fargs and pargs if pairs has already been run, as all
-- the arguments will already have been copied over.
--]]
metatable.__index = function (t, key)
--[[
-- Fetches an argument when the args table is indexed. First we check
-- to see if the value is memoized, and if not we try and fetch it from
-- the argument tables. When we check memoization, we need to check
-- metaArgs before nilArgs, as both can be non-nil at the same time.
-- If the argument is not present in metaArgs, we also check whether
-- pairs has been run yet. If pairs has already been run, we return nil.
-- This is because all the arguments will have already been copied into
-- metaArgs by the mergeArgs function, meaning that any other arguments
-- must be nil.
--]]
if type(key) == 'string' then
key = options.translate[key]
end
local val = metaArgs[key]
if val ~= nil then
return val
elseif metatable.donePairs or nilArgs[key] then
return nil
end
for _, argTable in ipairs(argTables) do
local argTableVal = tidyVal(key, argTable[key])
if argTableVal ~= nil then
metaArgs[key] = argTableVal
return argTableVal
end
end
nilArgs[key] = 'h'
return nil
end
metatable.__newindex = function (t, key, val)
-- This function is called when a module tries to add a new value to the
-- args table, or tries to change an existing value.
if type(key) == 'string' then
key = options.translate[key]
end
if options.readOnly then
error(
'could not write to argument table key "'
.. tostring(key)
.. '"; the table is read-only',
2
)
elseif options.noOverwrite and args[key] ~= nil then
error(
'could not write to argument table key "'
.. tostring(key)
.. '"; overwriting existing arguments is not permitted',
2
)
elseif val == nil then
--[[
-- If the argument is to be overwritten with nil, we need to erase
-- the value in metaArgs, so that __index, __pairs and __ipairs do
-- not use a previous existing value, if present; and we also need
-- to memoize the nil in nilArgs, so that the value isn't looked
-- up in the argument tables if it is accessed again.
--]]
metaArgs[key] = nil
nilArgs[key] = 'h'
else
metaArgs[key] = val
end
end
local function translatenext(invariant)
local k, v = next(invariant.t, invariant.k)
invariant.k = k
if k == nil then
return nil
elseif type(k) ~= 'string' or not options.backtranslate then
return k, v
else
local backtranslate = options.backtranslate[k]
if backtranslate == nil then
-- Skip this one. This is a tail call, so this won't cause stack overflow
return translatenext(invariant)
else
return backtranslate, v
end
end
end
metatable.__pairs = function ()
-- Called when pairs is run on the args table.
if not metatable.donePairs then
mergeArgs(argTables)
metatable.donePairs = true
end
return translatenext, { t = metaArgs }
end
local function inext(t, i)
-- This uses our __index metamethod
local v = t[i + 1]
if v ~= nil then
return i + 1, v
end
end
metatable.__ipairs = function (t)
-- Called when ipairs is run on the args table.
return inext, t, 0
end
return args
end
return arguments