Módulo:Arguments

Origem: IRChelp Brasil - Wiki
Ir para navegação Ir para pesquisar


Este módulo facilita o processamento de argumentos passados por um comando #invoke. Ele é um meta-módulo, destinado ao uso por outros módulos, e não deve ser chamado diretamente por #invoke. Suas funcionalidades incluem:

  • Fácil remoção de espaços em torno dos argumentos e de argumentos em branco.
  • Argumentos podem ser passados ao mesmo tempo tanto pelo frame atual quanto pelo frame pai. (Mais detalhes abaixo.)
  • Argumentos podem ser passados diretamente a partir de outro módulo Lua ou do console de depuração.
  • Argumentos são obtidos quando necessários, o que evita (alguns) problemas com elementos <ref>...</ref>.
  • A maioria das funcionalidades pode ser personalizada.

Uso básico

Primeiro, você precisa carregar o módulo. Ele contém uma função, chamada getArgs.

local getArgs = require('Module:Arguments').getArgs

No cenário mais básico, você pode utilizar getArgs dentro de sua função principal, main. A variável args é uma tabela contendo os argumentos de #invoke. (Ver abaixo para detalhes.)

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

function p.main(frame)
	local args = getArgs(frame)
	-- O código principal do módulo vai aqui.
end

return p

No entanto, a prática recomendada é utilizar uma função apenas para o processamento dos argumentos de #invoke. Isso significa que se alguém chamar o seu módulo a partir de outro módulo Lua você não precisa ter o objeto frame disponível, o que melhora o desempenho.

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)
	-- O código principal do módulo vai aqui.
end

return p

Se você quer que várias funções utilizem os argumentos, e você também quer que eles sejam acessíveis a partir de #invoke, você pode utilizar uma função wrapper.

local getArgs = require('Module:Arguments').getArgs

local function makeInvokeFunc(funcName)
	return function (frame)
		local args = getArgs(frame)
		return p[funcName](args)
	end
end

local p = {}

p.func1 = makeInvokeFunc('_func1')

function p._func1(args)
	-- O código para a primeira função vai aqui.
end

p.func2 = makeInvokeFunc('_func2')

function p._func2(args)
	-- O código para a segunda função vai aqui.
end

return p

Opções

Estão disponíveis as seguintes opções. Elas são explicadas nas seções abaixo.

local args = getArgs(frame, {
	trim = false,
	removeBlanks = false,
	valueFunc = function (key, value)
		-- Código para processar um argumento
	end,
	frameOnly = true,
	parentOnly = true,
	parentFirst = true,
	wrappers = {
		'Predefinição:Um invólucro',
		'Predefinição:Outro invólucro'
	},
	readOnly = true,
	noOverwrite = true
})

Remoção de espaços e parâmetros em branco

Argumentos em branco geralmente confundem os programadores que tentam converter predefinições do MediaWiki para Lua. Na sintaxe das predefinições, as strings vazias e aquelas que consistem apenas de espaços em branco são consideradas equivalentes a falso. No entanto, em Lua, tais strings são consideradas equivalentes a verdadeiro. Isso significa que se você não prestar atenção ao lidar com estes argumentos durante o desenvolvimento de módulos em Lua, você pode tratar algo como verdadeiro quando na verdade deveria ser falso. Para evitar isso, por padrão este módulo remove todos os argumentos em branco.

Analogamente, espaços em branco podem causar problemas ao lidar com argumentos posicionais. Embora eles sejam removidos de parâmetros com nome vindos de #invoke, eles são preservados nos argumentos posicionais. Na maioria das vezes esses espaços extras não são desejados, então este módulo remove-os por padrão.

No entanto, algumas vezes você quer aceitar argumentos em branco como entrada e algumas vezes você quer manter espaços extras. Isso pode ser necessário para converter algumas predefinições exatamente da forma como foram escritas. Se você quer fazer isso, você pode definir os parâmetros trim e removeBlanks com o valor false.

local args = getArgs(frame, {
	trim = false,
	removeBlanks = false
})

Formatação personalizada dos argumentos

Algumas vezes você quer remover alguns argumentos em branco mas não outros, ou talvez converter os valores de todos os argumentos posicionais para minúsculas. Para fazer coisas deste tipo você pode usar a opção valueFunc. Este parâmetro aceita como entrada uma função que recebe dois parâmetros, key e value, e retorna um único valor. Este valor é o que será obtido ao acessar o campo key da tabela args.

Exemplo 1: esta função preserva os espaços em branco para o primeiro argumento posicional, mas remove-os dos demais e também remove os demais argumentos em branco.

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
})

Exemplo 2: esta função remove parâmetros em branco e converte todos os argumentos para minúsculas, mas não remove espaços dos argumentos posicionais.

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
})

Nota: a função acima falhará se receber como entrada algo que não seja do tipo string ou nil. Isso pode ocorrer se utilizar a função getArgs na função principal (main) do seu módulo, e aquela função for chamada por outro módulo Lua. Neste caso, você precisará conferir o tipo de sua entrada. Esse problema não ocorre se utilizar uma função especifica para lidar com argumentos de #invoke (isto é, se houver uma função p.main e uma p._main, ou algo parecido).

Exemplos 1 e 2 com verificação de tipos
Exemplo 1:
local args = getArgs(frame, {
	valueFunc = function (key, value)
		if key == 1 then
			return value
		elseif type(value) == 'string' then
			value = mw.text.trim(value)
			if value ~= '' then
				return value
			else
				return nil
			end
		else
			return value
		end
	end
})
Exemplo 2:
local args = getArgs(frame, {
	valueFunc = function (key, value)
		if type(value) == 'string' then
			value = mw.ustring.lower(value)
			if mw.ustring.find(value, '%S') then
				return value
			else
				return nil
			end
		else
			return value
		end
	end
})

Além disso, por favor note que a função valueFunc é chamada praticamente a cada vez que um argumento é requisitado da tabela args, etão se você se preocupa com o desempenho você deve se certificar de não fazer nada ineficiente com o seu código.

Frames e frames pais

Os argumentos da tabela args podem ser passados simultaneamente do frame atual ou de seu frame pai. Para entender o que isso significa, é mais fácil dar um exemplo. Digamos que termos um módulo chamado Módulo:ExampleArgs. Este módulo imprime os dois primeiros parâmetros posicionais que ele recebe.

Código do Módulo:ExampleArgs
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)
	local first = args[1] or ''
	local second = args[2] or ''
	return first .. ' ' .. second
end

return p

O Módulo:ExampleArgs é chamado pela Predefinição:ExampleArgs, que contém o código {{#invoke:ExampleArgs|main|firstInvokeArg}}. Isso produz como resultado "firstInvokeArg".

Agora, se chamarmos a Predefinição:ExampleArgs, acontece o seguinte:

Código Resultado
{{ExampleArgs}} firstInvokeArg
{{ExampleArgs|firstTemplateArg}} firstInvokeArg
{{ExampleArgs|firstTemplateArg|secondTemplateArg}} firstInvokeArg secondTemplateArg

Há três opções que você pode definir para alterar este comportamento: frameOnly, parentOnly e parentFirst. Se você definir frameOnly então só serão aceitos os argumentos passados do frame atual; se você definir parentOnly então só serão aceitos os argumentos passados do frame pai; e se você definir parentFirst os argumentos serão passados de ambos os frames, mas os do frame pai terão prioridade sobre o frame atual. Estes são os resultados em termos da Predefinição:ExampleArgs:

frameOnly

Código Resultado
{{ExampleArgs}} firstInvokeArg
{{ExampleArgs|firstTemplateArg}} firstInvokeArg
{{ExampleArgs|firstTemplateArg|secondTemplateArg}} firstInvokeArg

parentOnly

Código Resultado
{{ExampleArgs}}
{{ExampleArgs|firstTemplateArg}} firstTemplateArg
{{ExampleArgs|firstTemplateArg|secondTemplateArg}} firstTemplateArg secondTemplateArg

parentFirst

Código Resultado
{{ExampleArgs}} firstInvokeArg
{{ExampleArgs|firstTemplateArg}} firstTemplateArg
{{ExampleArgs|firstTemplateArg|secondTemplateArg}} firstTemplateArg secondTemplateArg

Notas:

  1. Se você definir tanto a opção frameOnly quanto a opção parentOnly, o módulo não vai obter nenhum argumento de #invoke. Isso provavelmente não é o que você quer.
  2. Em algumas situações pode não estar disponível um módulo pai, por exemplo, se for passado para getArgs o frame pai em vez do frame atual. Neste caso, somente os argumentos do frame serão utilizados (a não ser que parentOnly esteja definido, mas neste caso nenhum argumento será utilizado) e as opções parentFirst e frameOnly não terão qualquer efeito.

Invólucros

A opção wrappers é utilizada para especificar um número limitado de predefinições de invólucro, isto é, predefinições cujo único objetivo é chamar um módulo. Se o módulo detecta que está sendo chamado de uma predefinição de invólucro, ele procurará apenas argumentos do frame pai; caso contrário ele procurará apenas argumentos no frame passado para getArgs. Isso permite que os módulos sejam chamados tanto por #invoke quanto através de uma predefinição de invólucro sem a perda de desempenho associada à chacagem tanto do frame quanto do frame pai ao verificar cada argumento.

Por exemplo, o conteúdo da en:Template:Side box (excluindo o conteúdo das tags <noinclude>...</noinclude>) é {{#invoke:Side box|main}}. Não faz sentido procurar argumentos passados diretamente para a declaração #invoke desta predefinição, pois nenhum argumento jamais será especificado lá. Podemos evitar a busca destes argumentos passados para #invoke utilizando a opção parentOnly, mas se fizermos isso então a #invoke também não funcionará a partir de outras páginas. Se esse fosse o caso, o |text=Algum texto no código {{#invoke:Side box|main|text=Algum texto}} seria completamente ignorado, não importando em que página ele tivesse sido usado. Utilizando a opção wrappers para especificar 'Template:Side box' como um invólucro, podemos fazer com que {{#invoke:Side box|main|text=Algum texto}} funcione na maioria das páginas, sem exigir que o módulo tenha que procurar argumentos na própria página da en:Template:Side box.

Os invólucros podem ser especificados tanto como uma cadeia de caracteres (string) quanto como uma array de cadeias de caracteres.

local args = getArgs(frame, {
	wrappers = 'Predefinição:Predefinição de invólucro'
})


local args = getArgs(frame, {
	wrappers = {
		'Predefinição:Um invólucro',
		'Predefinição:Outro invólucro',
		-- Pode-se inserir qualquer número de invólucros aqui.
	}
})

Notas:

  1. O módulo detectará automaticamente se ele está sendo chamado da subpágina /Testes da predefinição, então não há necessidade de especificar as páginas de testes explicitamente.
  2. A opção wrappers sobrescreve as opções frameOnly, parentOnly e parentFirst. Se a opção wrappers estiver definida, nenhuma delas terá efeito.
  3. Se a opção wrappers estiver definida e não houver um frame pai disponível, o módulo sempre obterá os argumentos do frame passado para getArgs.

Escrevendo na tabela de argumentos

Algumas vezes pode ser útil escrever novos valores na tabela de argumentos. Isso é possível com a configuração padrão do módulo. (No entanto, tenha em mente que geralmente um estilo de programação melhor seria criar uma nova tabela com os seus novos argumentos e copiar os argumentos da tabela args conforme fossem necessários.)

args.foo = 'algum valor'

É possível alterar este comportamento com as opções readOnly e noOverwrite. Se for definido readOnly então não será possível escrever quaisquer valores na tabela args. Se for definido noOverwrite, então será possível incluir novos valores na tabela, exceto se eles fossem sobrescrever argumentos que foram passados por #invoke.

Elementos "ref"

Este módulo utiliza metatables para obter argumentos de #invoke. Isso permite acesso tanto aos argumentos do frame atual quanto do frame pai sem ter que utilizar a função pairs(). Isso ajuda se o seu módulo pode receber elementos <ref>...</ref> como entrada.

Assim que os elementos <ref>...</ref> são acessados em Lua, eles são processados pelo software do MediaWiki e a referência aparecerá na lista de referências do artigo. Se o seu módulo omite o elemento de referência de sua saída, você obterá uma referência fantasma - uma referência que aparece na lista de referências, mas sem números ligando-se a ela. Esse problema ocorreu com módulos que usam pairs() para detectar se devem ser utilizados argumentos do frame atual ou de seu pai, porque tais módulos processam automaticamente todos os argumentos disponíveis.

Este módulo resolve esse problema permitindo o acesso tanto aos argumentos do frame atual quanto aos do frame pai, ao mesmo tempo em que só requisita esses argumentos quando são necessários. No entanto, o problema ainda ocorrerá se você utilizar pairs(args) em outros lugares do seu módulo.

Limitações conhecidas

O uso de metatables também tem aspectos negativos. A maioria das ferramentas normais para tabelas em Lua não funcionarão adequadamente na tabela args, incluindo o operador #, a função next(), e as funções da biblioteca table. Se o uso disso é importante para o seu módulo, você deve utilizar a sua própria função de processamento de argumentos em vez deste módulo.

Ver também


-- 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