Ir al contenido
Menú principal
Menú principal
mover a la barra lateral
ocultar
Navegación
Portada
mantenimiento
Páginas nuevas
Página aleatoria
Cambios recientes
Páginas especiales
Ayuda
Comunidad
Portal de la comunidad
Centro de reportes
Tablón de solicitudes
Tutorial de edición
Políticas
Buscar
Buscar
Apariencia
Crear una cuenta
Acceder
Herramientas personales
Crear una cuenta
Acceder
Páginas para editores desconectados
más información
Contribuciones
Discusión
Edición de «
Módulo:Argumentos/doc
»
Módulo
Discusión
español
Leer
Editar código
Ver historial
Herramientas
Herramientas
mover a la barra lateral
ocultar
Acciones
Leer
Editar código
Ver historial
Actualizar
General
Lo que enlaza aquí
Cambios relacionados
Información de la página
Enlace corto
En otros proyectos
Apariencia
mover a la barra lateral
ocultar
Advertencia:
no has iniciado sesión. Tu dirección IP se hará pública si haces cualquier edición. Si
inicias sesión
o
creas una cuenta
, tus ediciones se atribuirán a tu nombre de usuario, además de otros beneficios.
Comprobación antispam. ¡
No
rellenes esto!
{{Traducción|ci=en|art=Module:Arguments/doc}} Este módulo provee un procesamiento fácil a los argumentos que pasan de <code>#invoke</code>. Es un [[:Categoría:Wikipedia:Metamódulos Lua|metamódulo]], pensado para ser usado por otros módulos, y no debería ser llamado directamente desde <code>#invoke</code>. Entre sus características se incluyen: *Eliminar espacios en blanco al principio y final de los valores (no implementado todavía) *Eliminar parámetros vacíos (no implementado todavía) *Los argumentos pueden ser pasados por el marco actual y el marco padre a la vez (no implementado todavía) *Los argumentos pueden ser pasados por otro módulo Lua o desde la [[depurador|consola de depuración]]. *La mayoría de las características pueden ser personalizadas. ==Uso básico== Para empezar, se debe cargar el módulo. Contiene una función, llamada <code>obtenerArgumentos</code>. <syntaxhighlight lang="lua"> local dameArgs = require('Módulo:Argumentos').obtenerArgumentos </syntaxhighlight> En el escenario más básico, se puede usar obtenerArgumentos dentro de la función principal (usualmente <code>main</code>). La variable <code>args</code> es una tabla que contiene los argumentos de #invoke. <syntaxhighlight lang="lua"> local dameArgs = require('Módulo:Argumentos').obtenerArgumentos local p = {} function p.main(marco) local args = dameArgs(marco) -- El código principal del módulo vas acá end return p </syntaxhighlight> Sin embargo, se recomienda usar una función solo para procesar los argumentos de #invoke. Esto significa que si se llama al módulo desde otro módulo Lua, no es necesario tener un objeto marco disponible, mejorando el rendimiento. <syntaxhighlight lang="lua"> local dameArgs = require('Módulo:Argumentos').obtenerArgumentos local p = {} function p.main(marco) local args = dameArgs(marco) return p._main(args) end function p._main(args) -- El código principal del módulo vas acá end return p </syntaxhighlight> Si se quiere múltiples funciones que usen los argumentos, y que también sean accesibles desde #invoke, puede usarse una función envolvente. <syntaxhighlight lang="lua"> local dameArgs = require('Módulo:Argumentos').obtenerArgumentos local function hazFuncInvoke(fn) return function (marco) local args = dameArgs(marco) return p[fn](args) end end local p = {} p.func1 = hazFuncInvoke('_func1') function p._func1(args) -- El código de la primera función va acá end p.func2 = hazFuncInvoke('_func2') function p._func2(args) -- El código de la segunda función va acá end return p </syntaxhighlight> === Opciones === Las siguientes opciones están disponible, y son explicadas en las secciones de abajo. <syntaxhighlight lang="lua"> local args = dameArgs(marco, { limpiarEspacios = false, removerVacios = false, fnValores = function (clave, valor) -- Código para procesar un argumento end, soloMarco = true, soloPadre = true, padrePrimero = true, envolventes = { 'Plantilla:Una plantilla envolvente', 'Plantilla:Otra plantilla envolvente' }, soloLectura = true, noSobreescribir = true }) </syntaxhighlight> === Eliminar espacios y vacios === <!-- Blank arguments often trip up coders new to converting MediaWiki templates to Lua. In template syntax, blank strings and strings consisting only of whitespace are considered false. However, in Lua, blank strings and strings consisting of whitespace are considered true. This means that if you don't pay attention to such arguments when you write your Lua modules, you might treat something as true that should actually be treated as false. To avoid this, by default this module removes all blank arguments. Similarly, whitespace can cause problems when dealing with positional arguments. Although whitespace is trimmed for named arguments coming from #invoke, it is preserved for positional arguments. Most of the time this additional whitespace is not desired, so this module trims it off by default. However, sometimes you want to use blank arguments as input, and sometimes you want to keep additional whitespace. This can be necessary to convert some templates exactly as they were written. If you want to do this, you can set the <code>trim</code> and <code>removeBlanks</code> arguments to <code>false</code>. --> <syntaxhighlight lang="lua"> local args = dameArgs(marco, { limpiarEspacios = false, removerVacios = false }) </syntaxhighlight> === Personalización del formato de los argumentos === Algunas veces se desea remover algunos argumentos en blanco pero no otros, o tal vez poner todos los argumentos posicionales en minúscula. Para hacer cosas como estas, se usa la opción <code>fnValores</code>. La entrada a esta opción debe ser una función que toma dos parámetros, <code>clave</code> and <code>value</code>, y devuelve un valor sencillo. Este valor es lo que se obtiene cuando acceda al campo <code>clave</code> en la tabla de <code>args</code> Ejemplo 1: esta función preserva los espacio en blanco para el primer argumento posicional, pero los elimina de los otros argumentos, y los elimina si quedan vacíos: <syntaxhighlight lang="lua"> local args = dameArgs(marco, { fnValores = function (clave, valor) if 1 == clave then return valor elseif valor then valor = mw.text.trim(valor) -- Elimina los espacios al comienzo y final del valor if '' ~= valor then -- Si el valor no quedó vacío return valor -- Lo devuelve end end return nil -- En otros casos, devuelve el valor nulo (es decir, no incluir el valor) end }) </syntaxhighlight> Ejemplo 2: esta función elimina los argumentos vacíos y convierte todos los argumentos a minúsculas, pero no elimina los espacios del comienzo y final de los parámetros posicionales. <syntaxhighlight lang="lua"> local args = dameArgs(marco, { fnValores = function (clave, valor) if not valor then return nil end value = mw.ustring.lower(valor) if mw.ustring.find(valor, '%S') then return valor end return nil end }) </syntaxhighlight> Nota: las funciones de arriba fallarán si se les pasa una entrada que no sea de tipo <code>string</code> or <code>nil</code>. Esto puede suceder si se usa la función <code>dametArgs</code> en la función principal del módulo, y esa función es llamada desde otro módulo Lua. En este caso, es necesario comprobar el tipo de la entrada. Esto no es un problema cuando se usa una función específicamente para obtener los argumentos de #invoke; por ejemplo, cuando se usa una función para ese caso (usualmente <code>p.main</code>) y otra ser usada por otros módulos (usualmente <code>p._main</code>). <!-- {{cot|Examples 1 and 2 with type checking}} Example 1: <syntaxhighlight lang="lua"> 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 }) </syntaxhighlight> Example 2: <syntaxhighlight lang="lua"> 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 }) </syntaxhighlight> {{cob}} --> También, es importante destacar que la función <code>fnValores</code> es llamada aproximadamente cada vez que se pide un argumento de la tabla <code>args</code>. Por lo tanto, si se quiere mejorar el rendimiento debería verificarse no estar haciando nada ineficiente en ese código. === Marcos y marcos padre === Los argumentos de la tabla <code>args</code> pueden ser pasados desde el marco actual o del marco padre a la vez. Para enteder qué significa esto, es más fácil dar un ejemplo. Digamos que tenemos un módulo llamado <code>Módulo:EjemploArgs</code>, qu eimprime los primeros dos parámetros posicionales que se le pasen: <!-- {{cot|Module:ExampleArgs code}} <syntaxhighlight lang="lua"> 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 </syntaxhighlight> {{cob}} <code>Module:ExampleArgs</code> is then called by <code>Template:ExampleArgs</code>, which contains the code <code><nowiki>{{#invoke:ExampleArgs|main|firstInvokeArg}}</nowiki></code>. This produces the result "firstInvokeArg". Now if we were to call <code>Template:ExampleArgs</code>, the following would happen: {| class="wikitable" style="width: 50em; max-width: 100%;" |- ! style="width: 60%;" | Code ! style="width: 40%;" | Result |- | <code><nowiki>{{ExampleArgs}}</nowiki></code> | firstInvokeArg |- | <code><nowiki>{{ExampleArgs|firstTemplateArg}}</nowiki></code> | firstInvokeArg |- | <code><nowiki>{{ExampleArgs|firstTemplateArg|secondTemplateArg}}</nowiki></code> | firstInvokeArg secondTemplateArg |} There are three options you can set to change this behaviour: <code>frameOnly</code>, <code>parentOnly</code> and <code>parentFirst</code>. If you set <code>frameOnly</code> then only arguments passed from the current frame will be accepted; if you set <code>parentOnly</code> then only arguments passed from the parent frame will be accepted; and if you set <code>parentFirst</code> then arguments will be passed from both the current and parent frames, but the parent frame will have priority over the current frame. Here are the results in terms of <code>Template:ExampleArgs</code>: ; frameOnly {| class="wikitable" style="width: 50em; max-width: 100%;" |- ! style="width: 60%;" | Code ! style="width: 40%;" | Result |- | <code><nowiki>{{ExampleArgs}}</nowiki></code> | firstInvokeArg |- | <code><nowiki>{{ExampleArgs|firstTemplateArg}}</nowiki></code> | firstInvokeArg |- | <code><nowiki>{{ExampleArgs|firstTemplateArg|secondTemplateArg}}</nowiki></code> | firstInvokeArg |} ; parentOnly {| class="wikitable" style="width: 50em; max-width: 100%;" |- ! style="width: 60%;" | Code ! style="width: 40%;" | Result |- | <code><nowiki>{{ExampleArgs}}</nowiki></code> | |- | <code><nowiki>{{ExampleArgs|firstTemplateArg}}</nowiki></code> | firstTemplateArg |- | <code><nowiki>{{ExampleArgs|firstTemplateArg|secondTemplateArg}}</nowiki></code> | firstTemplateArg secondTemplateArg |} ; parentFirst {| class="wikitable" style="width: 50em; max-width: 100%;" |- ! style="width: 60%;" | Code ! style="width: 40%;" | Result |- | <code><nowiki>{{ExampleArgs}}</nowiki></code> | firstInvokeArg |- | <code><nowiki>{{ExampleArgs|firstTemplateArg}}</nowiki></code> | firstTemplateArg |- | <code><nowiki>{{ExampleArgs|firstTemplateArg|secondTemplateArg}}</nowiki></code> | firstTemplateArg secondTemplateArg |} Notes: # If you set both the <code>frameOnly</code> and <code>parentOnly</code> options, the module won't fetch any arguments at all from #invoke. This is probably not what you want. # In some situations a parent frame may not be available, e.g. if getArgs is passed the parent frame rather than the current frame. In this case, only the frame arguments will be used (unless parentOnly is set, in which case no arguments will be used) and the <code>parentFirst</code> and <code>frameOnly</code> options will have no effect. --> === Envolventes === La opción ''envolventes'' se usa para indicar un número limitado de plantillas que funcionan como envolentes; es decir, cuyo único propósito es llamar al módulo. Si el módulo detecta que es llamado desde una de estas plantillas, solo comprobará los argumentos del marco padre; de lo contrario solo lo hará con el marco pasado a <code>dameArgs</code>. Esto le permite al módulo ser llamado tanto desde #invoke como desde una envolvente sin la pérdida de rendimiento asociada a tener que comprobar ambos marcos (el actual y el padre) por cada argumento. <!-- For example, the only content of [[Template:Side box]] (excluding content in {{tag|noinclude}} tags) is <code><nowiki>{{#invoke:Side box|main}}</nowiki></code>. There is no point in checking the arguments passed directly to the #invoke statement for this template, as no arguments will ever be specified there. We can avoid checking arguments passed to #invoke by using the ''parentOnly'' option, but if we do this then #invoke will not work from other pages either. If this were the case, the {{para|text|Some text}} in the code <code><nowiki>{{#invoke:Side box|main|text=Some text}}</nowiki></code> would be ignored completely, no matter what page it was used from. By using the <code>wrappers</code> option to specify 'Template:Side box' as a wrapper, we can make <code><nowiki>{{#invoke:Side box|main|text=Some text}}</nowiki></code> work from most pages, while still not requiring that the module check for arguments on the [[Template:Side box]] page itself. Wrappers can be specified either as a string, or as an array of strings. <syntaxhighlight lang="lua"> local args = getArgs(frame, { wrappers = 'Template:Wrapper template' }) </syntaxhighlight> <syntaxhighlight lang="lua"> local args = getArgs(frame, { wrappers = { 'Template:Wrapper 1', 'Template:Wrapper 2', -- Any number of wrapper templates can be added here. } }) </syntaxhighlight> Notes: # The module will automatically detect if it is being called from a wrapper template's /sandbox subpage, so there is no need to specify sandbox pages explicitly. # The ''wrappers'' option effectively changes the default of the ''frameOnly'' and ''parentOnly'' options. If, for example, ''parentOnly'' were explicitly set to false with ''wrappers'' set, calls via wrapper templates would result in both frame and parent arguments being loaded, though calls not via wrapper templates would result in only frame arguments being loaded. # If the ''wrappers'' option is set and no parent frame is available, the module will always get the arguments from the frame passed to <code>getArgs</code>. --> === Escribiendo en la tabla args === <!-- Sometimes it can be useful to write new values to the args table. This is possible with the default settings of this module. (However, bear in mind that it is usually better coding style to create a new table with your new values and copy arguments from the args table as needed.) <syntaxhighlight lang="lua"> args.foo = 'some value' </syntaxhighlight> It is possible to alter this behaviour with the <code>readOnly</code> and <code>noOverwrite</code> options. If <code>readOnly</code> is set then it is not possible to write any values to the args table at all. If <code>noOverwrite</code> is set, then it is possible to add new values to the table, but it is not possible to add a value if it would overwrite any arguments that are passed from #invoke. --> === Etiquetas ref === <!-- This module uses [[mw:Extension:Scribunto/Lua reference manual#Metatables|metatables]] to fetch arguments from #invoke. This allows access to both the frame arguments and the parent frame arguments without using the <code>pairs()</code> function. This can help if your module might be passed {{tag|ref}} tags as input. As soon as {{tag|ref}} tags are accessed from Lua, they are processed by the MediaWiki software and the reference will appear in the reference list at the bottom of the article. If your module proceeds to omit the reference tag from the output, you will end up with a phantom reference - a reference that appears in the reference list, but no number that links to it. This has been a problem with modules that use <code>pairs()</code> to detect whether to use the arguments from the frame or the parent frame, as those modules automatically process every available argument. This module solves this problem by allowing access to both frame and parent frame arguments, while still only fetching those arguments when it is necessary. The problem will still occur if you use <code>pairs(args)</code> elsewhere in your module, however. --> === Limitaciones conocidas === <!-- The use of metatables also has its downsides. Most of the normal Lua table tools won't work properly on the args table, including the <code>#</code> operator, the <code>next()</code> function, and the functions in the table library. If using these is important for your module, you should use your own argument processing function instead of this module. --> <includeonly>{{#ifeq:{{SUBPAGENAME}}|sandbox|| [[Categoría:Wikipedia:Metamódulos Lua]] }}</includeonly>
Resumen:
Ten en cuenta que todas las contribuciones a Netxipedia se consideran publicadas bajo la Creative Commons Atribución-CompartirIgual (véase
Netxipedia:Derechos de autor
para más información). Si no deseas que las modifiquen sin limitaciones y las distribuyan libremente, no las publiques aquí.
Al mismo tiempo, asumimos que eres el autor de lo que escribiste, o lo copiaste de una fuente en el dominio público o con licencia libre.
¡No uses textos con copyright sin permiso!
Cancelar
Ayuda de edición
(se abre en una ventana nueva)
Plantillas usadas en esta página:
Plantilla:Aviso
(
ver código
) (protegida)
Plantilla:Obtener idioma
(
editar
)
Plantilla:Traducción
(
editar
)
Buscar
Buscar
Edición de «
Módulo:Argumentos/doc
»
Añadir tema