Extension:Scribunto/Lua reference manual/es

Este manual documenta como es usado en MediaWiki con la extensión. Algunas partes están derivadas del manual de referencia de Lua 5.1, que está disponible bajo la licencia MIT.



Primeros pasos
En una wiki MediaWiki con Scribunto habilitado, crear una página con un título que empieza con "Módulo:", por ejemplo "Módulo:Plátanos". En esta página nueva, copiar el siguiente texto:

Salva que, entonces en otro (no-módulo) página, escribe:

Exceptúa que tendrías que reemplazar "Plátanos" con cualquier  llamaste vuestro módulo. Esto llamará el "hola" la función exportada de aquel módulo. El $ 1 será reemplazado con el texto que la función regresó, en este caso, "$ 2 "

Es generalmente una idea buena de invocar Lua código del contexto de una plantilla. Esto significa que de la perspectiva de una página de llamar, la sintaxis es independiente de si la lógica de plantilla está implementada en Lua o en wikitext. También evita la introducción de sintaxis compleja adicional al contenido namespace de un wiki.

Estructura de módulo
El módulo él tiene que regresar un Lua la mesa que contiene las funciones que se puede apellidar por $ 1. Generalmente, cuando mostrado encima, una variable local está declarada aguantando una mesa, las funciones están añadidas a esta mesa, y la mesa está regresada al final del código de módulo.

Cualquiera funciona aquello no es añadido a esta mesa, si local o global, no será accesible por $ 1, pero globals podría ser accesible de otros módulos cargados utilizando $requerir_función. Es generalmente estilo bueno para el módulo para declarar todas las funciones y lugareño de variables.

Accediendo parámetros de wikitext
Las funciones llamaron por  será pasado un parámetro solo, aquello siendo un objeto de marco. Para acceder los parámetros pasaron al $ 1, el código típicamente utilizará el args mesa de aquel objeto de marco. Es también posible de acceder los parámetros pasaron a la plantilla que contiene el  por utilizar  frame:getParent  y accediendo que marco  $ 3.

Este objeto de marco es también utilizado para acceder contexto-características concretas del wikitext parser, como llamando parser funciones, expandiendo plantillas, y expandiendo arbitrario wikitext cuerdas.

Regresando texto
La función de módulo normalmente tendría que regresar una cuerda sola; cualesquier valores están regresados será pasado a través de $ 1 y entonces concatenado sin separator. Esta cuerda está incorporada al wikitext como el resultado del.

Al llegar a este punto en la página parse, las plantillas ya han sido expandidas, parser funciones y etiquetas de extensión ya han sido procesadas, y pre-salvar transforma (p. ej. firma tilde expansión y el de tubo de la ayuda) ha ya pasó. Por lo tanto el módulo no puede utilizar estas características en su texto de producción. Por ejemplo, si unos regresos de módulo $ 1, la página leerá "$ 2 ".

Por otro lado, subst está manejado en una etapa más temprana de procesar, tan con $ 1 sólo otro intentó las sustituciones serán procesadas. Desde la sustitución fallada quedará en el wikitext, entonces serán procesados en el próximos editar. Esto generalmente tendría que ser evitado.

Documentación de módulo
Scribunto Deja módulos para ser documentados por automáticamente asociando el módulo con un wikitext página de documentación; por default, el "/doc" subpage del módulo está utilizado para este propósito y es transcluded por encima del código de fuente del módulo en la página de módulo. Por ejemplo, la documentación para "Módulo:los plátanos" serían en "Módulo:Plátanos/doc".

Esto se puede configurar usando los siguientes Mensajes de espacio de nombres de MediaWiki:


 *  Escribunto-doc-página-nombra': Conjuntos el nombre de la página utilizada para documentación. El nombre del módulo (sin el Módulo: prefijo) está pasado como $1. Si en el módulo namespace, las páginas especificaron aquí será interpretado como wikitext más que Lua fuente y no puede ser utilizado con . El default es "Módulo:$ 1 /doc", i.e. el /doc subpage del módulo. Nota que parser las funciones y otra expansión de tirante no pueden ser utilizadas en este mensaje.
 *  Escribunto-doc-página--no-existir': el mensaje mostrado cuándo el doc la página no existe. El nombre de la página está pasado como $ . El default es vacío.
 *  Escribunto-doc-página-muestra': el mensaje mostrado cuándo el doc la página existe. El nombre de la página está pasado como $ . El default es a transclude la página de documentación.
 *  Escribunto-doc-página-encabezamiento': el encabezamiento mostrado cuándo viendo la página de documentación él. El nombre del módulo (con Módulo: prefijo) siendo documentado está pasado como $1. El default sencillamente muestra explicación a escasa en cursiva.

Nota que los módulos no pueden ser directamente categorized y no puede tener interwiki los enlaces directamente añadieron. Estos podrían ser colocados en la página de documentación dentro de $ 1 etiquetas, donde serán aplicados al módulo cuándo la página de documentación es transcluded a la página de módulo.

Fichas
Un nombre (también llamó un identificador) en Lua puede ser cualquier cuerda de letras, dígitos, y underscores, no empezando con un dígito. Los nombres son caso -sensibles; "foo", "Foo", y "FOO" es todos los nombres diferentes.

Las palabras clave siguientes están reservadas y no puede ser utilizado como nombres:



Los nombres que empiezan con un underscore siguió por las letras mayúsculas están reservadas para internos Lua variables globales.

Otros Fichas es:



Comentarios
Unos inicios de comentario con un  anywhere fuera de una cuerda. Si el $ 1 es inmediatamente seguido por un paréntesis largo de apertura, el comentario continúa al correspondiente cerrando paréntesis largo; otherwise las carreras de comentario hasta el final de la línea actual.

Tipos de datos
Lua Es una lengua dinámicamente escrita, el cual significa que variables y argumentos de función no tienen ningún tipo, sólo los valores asignaron a ellos. Todos los valores llevan un tipo.

Lua Tiene ocho dato básico tipos, aun así sólo seis es pertinente al Scribunto extensión. El $función_de función del tipo regresará el tipo de un valor.

El $tostring_función de función convertirá un valor a una cuerda. El $tonumber_función de función convertirá un valor a un número si es posible, y otherwise regresará cero. hay no funciones explícitas para convertir un valor a otros tipos de dato.

Los números son automáticamente convertidos a las cuerdas cuándo utilizadas dónde una cuerda está esperada, p. ej. cuándo utilizado con el operador de concatenación. Las cuerdas reconocieron por $tonumber_la función es automáticamente convertida a los números cuándo utilizados con operadores de aritmética. Cuándo un valor booleano está esperado, todo valora otro que cero y falso está considerado para ser cierto.

Cero
"El cero" es el tipo de dato de $ 1, el cual existe para representar la ausencia de un valor.

El cero no puede ser utilizado como clave en una mesa, y no hay ninguna diferencia entre un no asignado llave de mesa y una llave asignaron un valor de cero.

Cuándo convertido a una cuerda, el resultado es cero "". Cuándo convertido a booleano, el cero está considerado falso.

booleano
Los valores booleanos son $ 1 y $ 2.

Cuándo convertido a una cuerda, el resultado es "cierto" o "falso".

Diferente muchos otras lenguas, los valores booleanos no pueden ser directamente convertidos a números. Y diferente muchos otras lenguas, sólo falsos y el cero está considerado falso para conversión booleana; el número 0 y la cuerda vacía es #ambos consideró cierto.

Cuerda
Lua Las cuerdas están consideradas una serie de 8-mordió bytes;  es hasta la aplicación para interpretarles en cualquier particular codificando.

Cuerda literals puede ser delimitado por cualquier solo o doble cita ($ 1 o $ 2 ); gusta Javascript y PHP diferente, no hay ninguna diferencia entre el dos. Las secuencias de escapada siguientes están reconocidas:


 * (campana, byte 7)
 * (backspace, byte 8)
 * (Tabulador horizontal, byte 9)
 * (newline, byte 10)
 * (Tabulador vertical, byte 11)
 * (La forma alimenta, byte 12)
 * (Retorno de carro, byte 13)
 * \" (Doble cita, byte 34)
 * (Solo cita, byte 39)
 * (backslash, byte 92)

Un literal newline también puede ser incluido en una cuerda por preceder él con un backslash. Los bytes también pueden ser especificados utilizando una secuencia de escapada '\ddd', donde ddd es el valor decimal del byte en la gama 0@–255. Para incluir Unicode los caracteres que utilizan secuencias de escapada, los bytes individuales para el UTF-8 codificando tiene que ser especificado; en general, sea más sincero de introducir el Unicode caracteres directamente.

Las cuerdas literales también pueden ser definidas utilizando paréntesis largos. Un paréntesis largo de apertura consta de un paréntesis cuadrado de apertura seguido por cero o señales más iguales siguieron por otro paréntesis cuadrado de apertura, p. ej. $ 1, $ 2 , o $ 3. El paréntesis largo de apertura tiene que ser emparejado por el correspondiente cerrando paréntesis largo, p. ej. $ 1, $ 2 , o $ 3 Como caso especial, si un paréntesis largo de apertura es inmediatamente seguido por un newline entonces el newline no es incluido en la cuerda, pero un newline justo antes del cerrando el paréntesis largo está mantenido. Las cuerdas delimitaron por los paréntesis largos no interpretan secuencias de escapada.

Nota que todas las cuerdas están consideradas ciertas cuándo convertidos a booleanos. Esto es diferente la mayoría de otras lenguas, donde la cuerda vacía es normalmente considerada falso.

Número
Lua Ha sólo uno tipo numérico, el cual es típicamente representado internamente como doble-precisión valor de punto flotante. En este formato, enteros entre $ 1 y $ 2 puede ser representado exactamente, mientras números y números más grandes con una parte fraccionaria pueden adolecer ronda-fuera error.

Constantes de número están especificadas utilizando un periodo (.) Como decimal separator y sin agrupar separators, p. ej. 23456.78. Los números también pueden ser representados utilizando E notación sin espacios, p. ej. 1.23e-10, 123.45e20, o 1.23E5. Los enteros también pueden ser especificados en la notación hexadecimal que utiliza un  prefijo, p. ej. .

A pesar de que NaN e infinidades positivas y negativas son correctamente almacenadas y manejados, Lua no proporciona correspondiendo literals. La  constante.Enorme es infinidad positiva, cuando es una división como 1/0, y una división como 0/0 puede soler deprisa generar un NaN.

Nota que todos los números están considerados ciertos cuándo convertidos a booleanos. Esto es diferente la mayoría de otras lenguas, donde el número 0 es normalmente considerado falso. Cuándo convertido a una cuerda, los números finitos están representados en decimales, posiblemente en E notación; NaN es "nan" o "-nan"; y las infinidades son "inf" o "-inf".

tabla
Lua Las mesas son associative variedades, mucho gustar variedades de PHP y objetos de Javascript.

Las mesas están creadas utilizando curly tirantes. La mesa vacía es $ 1. Para poblar campos encima creación, una coma- y/o punto y coma-la lista separada de especificadores de campo puede ser incluida en los tirantes. Estos toman cualquiera de varias formas:


 * [expresión1] = expresión2 usos el (primero) valor de expresión1 como el clave y el (primero) valor de expresión2 como el valor.
 * nombre = expresión es equivalente a ["nombre"] = expresión
 * expresión es aproximadamente equivalente a [i] = expresión, donde i es un entero que empieza en 1 y incrementing con cada especificación de campo de esta forma. Si esto es el último especificador de campo y la expresión tiene valores múltiples, todos los  valores están utilizados; otherwise sólo el primero está mantenido.

Los campos en una  están accedidos utilizando notación de paréntesis, p. ej. . Llaves de cuerda que es también válido nombres también puede ser accedido utilizando notación de punto, p. ej. mesa.Clave es equivalente de someter['llave']. Llamando una función que es un valor en la  puede utilizar notación de colon; por ejemplo, mesa:func( ... ), El cual es equivalente de someter['func']( mesa, ... ) O mesa.func( Mesa, ... ).

Un ' esequence'' es una mesa con no-valores de cero para todos los enteros positivos de 1 a N y ningún valor (cero) para todos los enteros  positivos más grandes que N. Muchos Lua las funciones operan sólo en secuencias, e ignorar no-llaves de entero positivo.

Diferente muchos otras lenguas como PHP o Javascript, cualquier valor exceptúa cero y NaN puede ser utilizado como clave y ninguna conversión de tipo está actuada. Estos son todo válidos y distintos:

De modo parecido, cualquier valor exceptúa el cero puede ser almacenado como valor en una mesa. Almacenando el cero es equivalente a eliminar la llave de la mesa, y accediendo cualquier clave aquello no ha sido puesto resultará en un valor de cero.

Nota que las mesas nunca son implícitamente copiados en Lua; si una mesa está pasada como un argumento a la función y la función manipula las llaves o valores en la mesa, aquellos cambios serán visibles en el llamador.

Cuándo convertido a una cuerda, el resultado habitual es mesa "" pero puede ser overridden utilizando el __ metamethod. Incluso la mesa vacía está considerada cierta como booleano.

Función
Funciones en Lua es primero-valores de clase: pueden ser creados anónimamente, pasados como argumentos, asignados a variables, y tan encima.

Las funciones están creadas utilizando la palabra clave de función, y llamó utilizar paréntesis. azúcar Sintáctico es disponible para nombró funciones, funciones locales, y funciona que a acto le gustan funciones de miembro a una mesa. Ve Función declarations y [[$ancla2|llamadas de  abajo para detalles.

Lua Las funciones son clausuras, significando que mantienen una referencia al alcance en qué  están declarados y puede acceder y manipular variables en aquel alcance.

Como mesas, si una función está asignada a una variable diferente o pasado como un argumento a otra función, es todavía el mismo objeto "de función subyacente" que se apellidará.

Cuándo convertido a una cuerda, el resultado es función "".

Tipos no admitidos
El userdata el tipo suele control valores opacos para extensiones a Lua escritos en otras lenguas; por ejemplo, un userdata podría soler aguantar un C puntero o struct. Para dejar para uso de Scribunto en hosting entornos donde hechos de encargo-el código compilado no es dejado, no tales extensiones están utilizadas.

El hilo el tipo representa los mangos para coroutines, los cuales no son disponibles en Scribunto sandbox.

Metatables
Cada mesa puede tener una mesa asociada sabida como ' soyetatable''. Los campos en el metatable está utilizado por algunos operadores y funciones para especificar diferentes o fallback comportamiento para la mesa. El metatable para una mesa puede ser accedida utilizando el getmetatable función, y puesto con el setmetatable función.

Cuándo siendo accedido para su meta funciones, metatable los campos están accedidos como si con rawget.

Metatable Campos que afecta la mesa él es:
 * __index
 * Esto está utilizado cuándo un acceso de mesa  regresaría cero. Si el valor de este campo es una mesa, el acceso será repetido en aquella mesa, i.e. __  (cuáles pueden invocar aquella mesa  metatable  __índice). Si el valor de este campo es una función, la función se apellidará tan __índice( t, llave ). El rawget función bypasses esto metamethod.


 * __newindex
 * Esto está utilizado cuándo asignando un clave a una mesa t[clave] = valor donde rawget( t, llave ) regresaría cero. Si el valor de este campo es una mesa, la asignación será repetida en aquella mesa, i.e. __newindex[clave] = valor (cuáles pueden invocar aquella mesa metatable  __newindex). Si el valor de este campo es una función, la función se apellidará tan __newindex( t, llave, valor ). El rawset función bypasses esto metamethod.


 * __call
 * Esto está utilizado cuándo sintaxis de llamada de la función está utilizado en una mesa, t( ··· ). El valor tiene que ser una función, el cual se apellida tan a algo le gusta __la llamada( t, ··· ).


 * __mode
 * Esto suele la marca somete aguantar referencias débiles. El valor tiene que ser una cuerda . Por default, cualquier valor que está utilizado como clave o como valor en una mesa no será la basura recogió. Pero si este metafield contiene la letra 'k', las llaves pueden ser basura recogidos si  hay ninguna referencia no débil, y si  contiene 'v' los valores pueden ser; en cualquier caso, tanto la llave correspondiente y el valor están sacados de la mesa. Nota que el comportamiento es undefined si este campo está alterado después de la mesa está utilizada como metatable.

Otro metatable los campos incluyen:


 * __add†
 * __sub†
 * __mul†
 * __div†
 * __mod†
 * __pow†
 * __unm
 * __concat†
 * __eq‡
 * __lt‡
 * __le‡
 * __pairs
 * __ipairs
 * __metatable*
 * __tostring

† Para operadores binarios, Lua mira primero en el argumento izquierdo metatable (si cualquier) entonces el correcto es cuándo buscando un metamethod para utilizar. ‡ Para operadores relacionales, el metamethod es sólo utilizado si la misma función está especificada en ambos argumentos' metatables. Funciones anónimas diferentes, incluso con clausura y cuerpo idénticos, no puede ser considerado igual. * __metatable Afecta ambos getmetatable y setmetatable

Nota: En Lua, todas las   también comparten un solos metatable, en qué __índice refiere al de ancla mesa. Este metatable no es accesible en Scribunto, ni es el referenced mesa de cuerda; la mesa de cuerda disponible a los módulos es una copia.

Variables
Las variables son coloca que valores de tienda. Hay tres clases de variables en Lua: variables globales, variables locales, y campos de mesa.

Un de ancla representa una variable global o local (o un argumento de función, el cual es justo una clase de variable local). Las variables están supuestas para ser globales a no ser que explícitamente declarados como  utilizando la palabra clave local. Cualquier variable aquello no ha sido asignado un valor está considerado para tener un valor de cero.

Las variables lobales están almacenadas en un estándares Lua la mesa llamó un entorno; esta mesa es a menudo disponible como el G variable _global. Es posible de poner un metatable para esta mesa variable global; el __índice y __newindex metamethods se apellidará para accesos de y asignaciones a variables globales tan ellos para accesos de y asignaciones a campos en cualquier otra mesa.

El entorno para una función puede ser accedido utilizando el getfenv función y cambió utilizar el setfenv función; en Scribunto, estas funciones son severamente restringidas si son disponibles en absoluto.

Las variables locales son léxicamente scoped; ve Local variable declarations para detalles.

Expresiones
Un expresión es algo aquello tiene valores: literals (números, cuerdas, ciertos, falsos, cero), función anónima declarations, constructores de mesa, referencias variables, llamadas de función, el vararg expresión, las expresiones envolvieron en paréntesis, unary los operadores aplicaron a expresiones, y las expresiones combinaron con operadores binarios.

La mayoría de expresiones tienen uno valora; llamadas de función y el vararg la expresión puede tener cualquier número. Nota que envolviendo una llamada de función o vararg la expresión en paréntesis perderá todo excepto el primer valor.

Listas de expresión son coma -separó listas de expresiones. Todos excepto la última expresión están forzados a un valor (cayendo valores adicionales, o utilizando cero si la expresión no tiene ningún valor); todos los valores de la última expresión están incluidos en los valores de la lista de expresión.

Operadores de aritmética
Lua Apoya los operadores de aritmética habituales: adición, sustracción, multiplicación, división, modulo, exponentiation, y negación.

Cuando todos los operandos son números o cuerdas  para qué $ 1 regresos no-cero, las operaciones tienen su significado habitual.

Si cualquier operando es una mesa con un apropiado $ 1, el metamethod se apellidará.

Operadores relacionales
Los operadores relacionales en Lua es $ 1, $ 2 , $ 3 , $ 4 , $ 5 , y $ 6. El resultado de un operador relacional es siempre un booleano.

Igualdad ($ 1 ) primero compara los tipos de sus operandos; si son diferentes, el resultado es falso. Entonces compara los valores: cero, booleano, número, y la cuerda está comparada en la manera esperada. Las funciones son iguales si refieren al objeto de función mismo exacto; $ 2 regresará falso, cuando  está comparando dos funciones anónimas diferentes. Las mesas son por default comparados en la misma manera, pero esto puede ser cambiado utilizando el __eq metamethod.

Desigualdad ($ 1 ) es la negación exacta de igualdad.

Para los operadores de ordenar, si ambos son números o ambos son cuerdas,  están comparados directamente. Luego, metamethods está comprobado:


 * Unos   __  ! !* Un &lt;= b   __  si disponibles, o si __lt es disponible entonces  está considerado equivalente a no ( b
 *       
 * &gt;= b  b &lt;= un

Si el necesario metamethods no es disponible, un error está levantado.

Operadores lógicos
L s operadores lógicos son y, o, y. Todos utilizan la interpretación estándar donde cero y falso está considerado falso  cualquier cosa más está considerada cierta.

Para y, si el operando izquierdo está considerado falso entonces está regresado   el segundo operando no es evaluado; otherwise el segundo operando está regresado.

Para, si el operando izquierdo está considerado cierto entonces  está regresado y el segundo operando no es evaluado; otherwise el segundo operando está regresado.

Para, el resultado es siempre cierto o falso.

Nota aquello y    circuito corto. Por ejemplo, foo o barra sólo   de llamada si   regresa falso o cero como su primer valor.

Operador de concatenación
El operador de concatenación es dos puntos, utilizado como .. b. Si ambos operandos son números o cuerdas, están convertidos a cuerdas y concatenó. Otherwise Si  __concat metamethod es disponible,  está utilizado. Otherwise, un error está levantado.

Nota que Lua las cuerdas son inmutables y Lua no proporciona cualquier clase de "constructor de cuerda", así que  bucle que repetidamente hace un = un .. b Tendrá que crear una cuerda nueva para cada iteración y finalmente basura-recoger las cuerdas viejas. Si muchas cuerdas necesitan concatenar, pueda ser más rápido de utilizar cuerda.Formato o para insertar todas las cuerdas a un secuencia y uso mesa.concat Al final.

Operador de longitud
El operador de longitud es #, utilizado como #un. Si  es una cuerda,  regresa la longitud en bytes. Si  es un de ancla mesa,  regresa la longitud de la secuencia.

Si un es a mesa que es no una secuencia, el #un puede regresar cualquier valor N tal que un[N] no es cero y un[N+1] es cero, incluso si  hay no-valores de cero en índices más altos. Por ejemplo,

Precedencia de operador
Lua precedencia de operador o de operaciones de operaciones, de más altos a más bajos:


 * 1) not # - (Negación)
 * 2) + - (Sustracción)
 * 3) and
 * or
 * 1) and
 * or
 * 1) and
 * or

Dentro de  nivel de precedencia, operadores más binarios quedan-associative, i.e. un / b / c está interpretado cuando (un / b) / c. Exponentiation Y la concatenación es correcta-associative, i.e. un ^ b ^ c está interpretado como ^ (b ^ c).

Llamadas de función
Lua Llamadas de función parecen aquellos en más otras lenguas: un nombre seguido por una lista de argumentos en paréntesis:

func( Expresión-lista )

Cuando es habitual con listas de expresión en Lua, la última expresión en la lista puede suministrar valores de argumento múltiple.

Si la función se apellida con menos valores en la lista de expresión que hay argumentos en la definición de función, los argumentos extras tendrán un valor de cero. Si la lista de expresión contiene más valores que hay argumentos, los valores sobrantes son discarded. Es también posible para una función para tomar un número variable de argumentos; ve de ancla declarations para detalles.

Lua También deja directo llamando de un valor de regreso de la ión, i.e. func. Si una expresión más complejo que un acceso variable está necesitado para determinar la función para apellidarse, un parenthesized la expresión puede ser utilizada en sitio del acceso variable.

Lua Tiene azúcar sintáctico para dos casos comunes. El primero es cuándo una mesa está siendo utilizada como un objeto, y la función es para apellidarse como método en el objeto. La sintaxis

Mesa:nombre( Expresión-lista )

Es exactamente equivalente a

table.name( Mesa, Expresión-lista )

El segundo caso común es Lua método de implementar nombró argumentos por pasar una mesa que contiene el nombre-a-mapeos de valor como el argumento posicional único a la función. En este caso, los paréntesis alrededor de la lista de argumento pueden ser omitidos. Esto también trabajos si la función es para ser pasado una cuerda literal sola. Por ejemplo, las llamadas

func{ arg1 = exp, arg2 = exp } func"string"

Es equivalente a

func( { arg1 = exp, arg2 = exp } ) func( "string" )

Estos pueden ser combinados; las llamadas siguientes son equivalentes:

table:name{ arg1 = exp, arg2 = exp } table.name( table, { arg1 = exp, arg2 = exp } )

Declaraciones de funciones
La sintaxis para funcionar declaration parece esto:

Función ( var-lista ) Bloque Fin

Todas las variables en var-lista es local a la función, con los valores asignaron de la lista de expresión en el de función de la ancla. Las variables locales adicionales pueden ser declaradas dentro del bloque.

Cuándo la función se apellida, las declaraciones en bloque está ejecutado después de las variables locales que corresponden a var-lista está creado y asignó valores. Si un de regreso de la ancla está logrado, el bloque está salido y los valores de la expresión de llamada de la función son aquellos dados por la declaración de regreso. Si la ejecución logra el fin del bloque de la función sin encontrar una declaración de regreso, el resultado de la expresión de llamada de la función tiene cero valores.

Lua Las funciones son clausuras léxicas. Un modismo común es para declarar "variables estáticas" privadas como lugareños en el alcance donde la función está declarada. Por ejemplo,

Una función puede ser declarada para aceptar un número variable de argumentos, por especificar ... Cuando el elemento final en el var-lista:

Función ( var-lista, ... ) de bloque Fin

Dentro del bloque, el varargs expresión ... Puede ser utilizado, con el resultado siendo todos los valores extras en la llamada de función. Por ejemplo,

El selecciona la función está diseñada para trabajar con el varargs expresión; en particular, selecciona( '#', ... ) Tendría que ser utilizado en vez de #{ ... } Para contar el número de valores en el varargs expresión, porque { ... } No puede ser un secuencia.

Lua Proporciona azúcar sintáctico para combinar función declaration y asignación a una variable; ve de ancla declaration declaraciones para detalles.

Nota que esto no trabajará:

 Función factorial = local ( n ) Si n <= 2 entonces Regreso n   Más Regreso n * factorial( n - 1 ) Fin Fin

Desde la función declaration está procesado antes de la declaración de asignación variable local es completa, "factorial" dentro del cuerpo de función refiere al (probablemente undefined) variable de aquel nombre en un alcance exterior. Este problema puede ser evitado por declarar la variable local primero y entonces asignando él en una declaración subsiguiente, o por utilizar el de ancla declaration declaración sintaxis.

Declaraciones
Un ' estatement'' es la unidad básica de ejecución: una asignación, estructura de control, llamada de función, variable declaration, etc.

Un chunk es una secuencia de declaraciones, opcionalmente separados por puntos y comas. Un chunk es básicamente consideró el cuerpo de una función anónima, así que pueda declarar variables locales, recibir argumentos, y valores de regreso.

Un bloque es también una secuencia de declaraciones, justo como un chunk. Un bloque puede ser delimitado para crear una declaración sola:. Estos pueden soler limitar el alcance de variables locales, o para añadir un  o   en medio de otro bloque.

Asignaciones
El variable-lista es una coma-lista separada de variables; el expresión-lista es una coma-lista separada de un o o más expresiones. Todas las expresiones están evaluadas antes de cualesquier asignaciones están actuadas, así que un, b = b, un  intercambio los valores de un y b.

Local variable declarations
Las variables locales pueden ser declaradas anywhere dentro de un bloque o chunk. La primera forma, sin una lista de expresión, declara las variables pero no asigna un valor así que todas las variables tienen cero como valor. La segunda forma asigna valores a las variables locales, cuando descritos en Asignaciones encima.

Nota que la visibilidad de la variable local empieza con la declaración después de la variable  declaration. Así que un declaration como local x = x declara un local variable x y lo asigna el valor de x del alcance exterior. Los restos variables locales en alcance hasta el fin del innermost el bloque que contiene la variable local declaration.

Estructuras de control
La declaración de rato repite un bloque mientras una expresión evalúa a un valor cierto.

El repetir la declaración repite un bloque hasta una expresión evalúa a un valor cierto. Las variables locales declararon dentro del bloque puede ser accedido en la expresión.

Esta primera forma del para el bucle declarará una variable local, y repetir el bloque para valores de exp1 a exp2 añadiendo exp3 en cada iteración. Nota aquello exp3 puede ser omitido enteramente, en qué caso 1 está utilizado, pero valores no numéricos como  y   es un error. Todas las expresiones están evaluadas una vez antes del bucle está empezado.

Esta forma del para el bucle es aproximadamente equivalente a Exceptúa que las variables var, límite, y el paso no es accesible anywhere más. Nota que el variable nombre es local al bloque; para utilizar el valor después del bucle, tenga que ser copiado a un variable declarado fuera del bucle.

La segunda forma del para trabajos de bucle con iterator funciones. Cuando en la primera forma, el expresión-lista está evaluado sólo una vez antes de empezar el bucle.

Esta forma del para el bucle es aproximadamente equivalente a Exceptúa que otra vez las variables func, estáticos, y var no es accesible anywhere más. Nota que las variables en var-lista es local al bloque; para utilizarles después de que el bucle, tienen que ser copiados a las variables declararon fuera del bucle.

A menudo el expresión-lista es una llamada de función sola que regresos los tres valores. Si el iterator la función puede ser escrita tan sólo depende de los parámetros pasaron a él, aquello sería el más eficaz. Si no, Programando en Lua sugiere que una clausura ser preferido a regresar una mesa como la variable estática y actualizando sus miembros en cada iteración.

Ejecuta bloque1 si exp1 los regresos ciertos, otherwise ejecuta bloque2 si exp2 los regresos ciertos, y bloque3 otherwise. El  la porción puede ser omitida, y el   la porción puede ser repetida u omitida como necesario.

La declaración de regreso suele valores de regreso de una función o un chunk (cuál es justo una función). El expresión-lista es una coma-lista separada de cero o más expresiones.

Lua Implementa de llamada de cola: si expresión-lista consta de exactamente una expresión qué es una llamada de función, el actual stack el marco será reused para la llamada a aquella función. Esto tiene implicación para funciones que trata la llamada stack, como getfenv y depura.traceback.

La declaración de regreso tiene que ser la última declaración en su de ancla. Si para algunos razonan un regreso está necesitado en medio de un bloque, un bloque explícito regresa el fin puede ser utilizado.

La declaración de rotura suele rescindir la ejecución de un rato, repite, o para bucle, skipping a la declaración próxima después del bucle.

La declaración de rotura tiene que ser la última declaración en su de ancla. Si para algunos razonan una rotura está necesitada en medio de un bloque, un bloque explícito rompe el fin puede ser utilizado.

Llamadas de función como declaraciones
Una llamada de función puede ser utilizada como declaración; en este caso, la función está apellidándose sólo para cualquier lado lo efectúa puede tener (p. ej. mw.Registro valores de registros) y cualesquier valores de regreso son discarded.

Declaraciones de declaración de función
Lua Proporciona azúcar sintáctico para hacer declarando una función y asignándolo a una variable más natural. Los pares siguientes de declarations es equivalente

-- Básico declaration Función func( var-lista ) de bloque fin func = Función ( var-lista ) de bloque fin

-- Función local Función local func( var-lista ) de bloque fin Lugareño func; func = función ( var-lista ) de bloque fin

-- Función como campo en una mesa Mesa de función.func( var-Lista ) de bloque fin Mesa.func = Función ( var-lista ) de bloque fin

-- Función como método en una mesa Mesa de función:func( var-lista ) de bloque fin Mesa.func = Función ( self, var-lista ) de bloque fin

Nota la notación de colon aquí parallels la notación de colon para llamadas de función, añadiendo un argumento implícito nombró "self" a principios de la lista de argumentos.

Error handling
Errors may be "thrown" using the error and assert functions. To "catch" errors, use pcall or xpcall. Note that certain internal Scribunto errors cannot be caught in Lua code.

Garbage collection
Lua performs automatic memory management. This means that you have to worry neither about allocating memory for new objects nor about freeing it when the objects are no longer needed. Lua manages memory automatically by running a garbage collector from time to time to collect all dead objects (that is, objects that are no longer accessible from Lua) and objects that are only reachable via weak references. All memory used by Lua is subject to automatic management: tables, functions, strings, etc.

Garbage collection happens automatically, and cannot be configured from within Scribunto.

Standard libraries
The standard Lua libraries provide essential services and performance-critical functions to Lua. Only those portions of the standard libraries that are available in Scribunto are documented here.

_G


This variable holds a reference to the current global variable table; the global variable  may also be accessed as. Note, however, that there is nothing special about _G itself; it may be reassigned in the same manner as any other variable:

The global variable table may be used just like any other table. For example,

_VERSION


A string containing the running version of Lua, e.g. "Lua 5.1".

assert
If  is nil or false, issues an error. In this case,  is used as the text of the error: if nil (or unspecified), the text is "assertion failed!"; if a string or number, the text is that value; otherwise assert itself will raise an error.

If  is any other value, assert returns all arguments including   and.

A somewhat common idiom in Lua is for a function to return a "true" value in normal operation, and on failure return nil or false as the first value and an error message as the second value. Easy error checking can then be implemented by wrapping the call in a call to :

error
Issues an error, with text.

normally adds some information about the location of the error. If  is 1 or omitted, that information is the location of the call to   itself; 2 uses the location of the call of the function that called error; and so on. Passing 0 omits inclusion of the location information.

getfenv
Note this function may not be available, depending on  in the engine configuration.

Returns an environment (global variable table), as specified by :


 * If 1, nil, or omitted, returns the environment of the function calling . Often this will be the same as _G.
 * Integers 2–10 return the environment of functions higher in the call stack. For example, 2 returns the environment for the function that called the current function, 3 returns the environment for the function calling that function, and so on. An error will be raised if the value is higher than the number of function calls in the stack, or if the targeted stack level returned with a tail call.
 * Passing a function returns the environment that will be used when that function is called.

The environments used by all standard library functions and Scribunto library functions are protected. Attempting to access these environments using  will return nil instead.

getmetatable
Returns the metatable of a table. Any other type will return nil.

If the metatable has a  field, that value will be returned instead of the actual metatable.

ipairs
Returns three values: an iterator function, the table, and 0. This is intended for use in the iterator form of :

for i, v in ipairs( t ) do    block end

This will iterate over the pairs ( 1, t[1] ), ( 2, t[2] ), and so on, stopping when t[i] would be nil.

The standard behavior may be overridden by providing an  metamethod. If that metamethod exists, the call to ipairs will return the three values returned by  instead.

next
This allows for iterating over the keys in a table. If  is nil or unspecified, returns the "first" key in the table and its value; otherwise, it returns the "next" key and its value. When no more keys are available, returns nil. It is possible to check whether a table is empty using the expression.

Note that the order in which the keys are returned is not specified, even for tables with numeric indexes. To traverse a table in numerical order, use a numerical for or ipairs.

Behavior is undefined if, when using next for traversal, any non-existing key is assigned a value. Assigning a new value (including nil) to an existing field is allowed.

pairs
Returns three values: an iterator function (next or a work-alike), the table, and nil. This is intended for use in the iterator form of :

This will iterate over the key-value pairs in  just as next would; see the documentation for next for restrictions on modifying the table during traversal.

The standard behavior may be overridden by providing a __pairs metamethod. If that metamethod exists, the call to pairs will return the three values returned by  instead.

pcall
Calls the function  with the given arguments in protected mode. This means that if an error is raised during the call to, pcall will return false and the error message raised. If no error occurs, pcall will return true and all values returned by the call.

In pseudocode,  might be defined something like this:

rawequal
This is equivalent to  except that it ignores any __eq metamethod.

rawget
This is equivalent to  except that it ignores any __index metamethod.

rawset
This is equivalent to  except that it ignores any __newindex metamethod.

select
If  is a number, returns all arguments in   after that index. If  is the string '#', returns the count of arguments in.

In other words,  is something roughly like the following except that it will work correctly even when   contains nil values (see documentation for # and unpack for the problem with nils).

setmetatable
Sets the metatable of a table. may be nil, but must be explicitly provided.

If the current metatable has a __metatable field,  will throw an error.

tonumber
Tries to convert  to a number. If it is already a number or a string convertible to a number, then  returns this number; otherwise, it returns nil.

The optional  (default 10) specifies the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35.

In base 10, the value may have a decimal part, be expressed in E notation, and may have a leading "0x" to indicate base 16. In other bases, only unsigned integers are accepted.

tostring
Converts  to a string. See Data types above for details on how each type is converted.

The standard behavior for tables may be overridden by providing a __tostring metamethod. If that metamethod exists, the call to tostring will return the single value returned by  instead.

type
Returns the type of  as a string: ,  ,  ,  ,  , or.

unpack
Returns values from the given table, something like  would do if written out manually. If nil or not given,  defaults to 1 and   defaults to.

Note that results are not deterministic if  is not a sequence and   is nil or unspecified; see Length operator for details.

xpcall
This is much like, except that the error message is passed to the function   before being returned.

In pseudocode,  might be defined something like this:

debug.traceback
Returns a string with a traceback of the call stack. An optional message string is appended at the beginning of the traceback. An optional level number tells at which stack level to start the traceback.

math.abs
Returns the absolute value of.

math.acos
Returns the arc cosine of  (given in radians).

math.asin
Returns the arc sine of  (given in radians).

math.atan
Returns the arc tangent of  (given in radians).

math.atan2
Returns the arc tangent of  (given in radians), using the signs of both parameters to find the quadrant of the result.

math.ceil
Returns the smallest integer larger than or equal to.

math.cos
Returns the cosine of  (given in radians).

math.cosh
Returns the hyperbolic cosine of.

math.deg
Returns the angle  (given in radians) in degrees.

math.exp
Returns the value $$e^x$$.

math.floor
Returns the largest integer smaller than or equal to.

math.fmod
Returns the remainder of the division of  by   that rounds the quotient towards zero. For example,  yields.

math.frexp
Returns two values  and   such that:


 * If  is finite and non-zero: $$x = m \times 2^e$$,   is an integer, and the absolute value of   is in the range $$[0.5, 1)$$
 * If  is zero:   and   are 0
 * If  is NaN or infinite:   is   and   is not specified

math.huge
The value representing positive infinity; larger than or equal to any other numerical value.

math.ldexp
Returns $$m \times 2^e$$ ( should be an integer).

math.log
Returns the natural logarithm of.

math.log10
Returns the base-10 logarithm of.

math.max
Returns the maximum value among its arguments.

Behavior with NaNs is not specified. With the current implementation, NaN will be returned if  is NaN, but any other NaNs will be ignored.

math.min
Returns the minimum value among its arguments.

Behavior with NaNs is not specified. With the current implementation, NaN will be returned if  is NaN, but any other NaNs will be ignored.

math.modf
Returns two numbers, the integral part of  and the fractional part of. For example,  yields.

math.pi
The value of $$\pi$$.

math.pow
Equivalent to.

math.rad
Returns the angle  (given in degrees) in radians.

math.random
Returns a pseudo-random number.

The arguments  and   may be omitted, but if specified must be convertible to integers.


 * With no arguments, returns a real number in the range $$[0,1)$$
 * With one argument, returns an integer in the range $$[1,m]$$
 * With two arguments, returns an integer in the range $$[m,n]$$

math.randomseed
Sets  as the seed for the pseudo-random generator.

Note that using the same seed will cause  to output the same sequence of numbers.

math.sin
Returns the sine of  (given in radians).

math.sinh
Returns the hyperbolic sine of.

math.sqrt
Returns the square root of. Equivalent to.

math.tan
Returns the tangent of  (given in radians).

math.tanh
Returns the hyperbolic tangent of.

os.clock
Returns an approximation of the amount in seconds of CPU time used by the program.

os.date

 * Language library's formatDate may be used for more comprehensive date formatting

Returns a string or a table containing date and time, formatted according to. If the format is omitted or nil, "%c" is used.

If  is given, it is the time to be formatted (see  ). Otherwise the current time is used.

If  starts with '!', then the date is formatted in UTC rather than the server's local time. After this optional character, if format is the string "*t", then date returns a table with the following fields:


 * year (full)
 * month (1–12)
 * day (1–31)
 * hour (0–23)
 * min (0–59)
 * sec (0–60)
 * wday (weekday, Sunday is 1)
 * yday (day of the year)
 * isdst (daylight saving flag, a boolean; may be absent if the information is not available)

If format is not "*t", then date returns the date as a string, formatted according to the same rules as the C function strftime.

os.difftime
Returns the number of seconds from  to.

os.time
Returns a number representing the current time.

When called without arguments, returns the current time. If passed a table, the time encoded in the table will be parsed. The table must have the fields "year", "month", and "day", and may also include "hour" (default 12), "min" (default 0), "sec" (default 0), and "isdst".

require
Loads the specified module.

First, it looks in  to see if the module is already loaded. If so, returns.

Otherwise, it calls each loader in the  sequence to attempt to find a loader for the module. If a loader is found, that loader is called. The value returned by the loader is stored into  and is returned.

See the documentation for  for information on the loaders available.

For example, if you have a module "Module:Giving" containing the following:

You can load this in another module with code such as this:

package.loaded
This table holds the loaded modules. The keys are the module names, and the values are the values returned when the module was loaded.

package.loaders
This table holds the sequence of searcher functions to use when loading modules. Each searcher function is called with a single argument, the name of the module to load. If the module is found, the searcher must return a function that will actually load the module and return the value to be returned by require. Otherwise, it must return nil.

Scribunto provides two searchers:


 * 1) Look in   for the loader function
 * 2) Look in the modules provided with Scribunto for the module name, and if that fails look in the Module: namespace. The "Module:" prefix must be provided.

Note that the standard Lua loaders are not included.

package.preload
This table holds loader functions, used by the first searcher Scribunto includes in package.loaders.

package.seeall
Sets the __index metamethod for  to _G.

String library
In all string functions, the first character is at position 1, not position 0 as in C, PHP, and JavaScript. Indexes may be negative, in which case they count from the end of the string: position -1 is the last character in the string, -2 is the second-last, and so on.

The string library assumes one-byte character encodings. It cannot handle Unicode characters. To operate on Unicode strings, use the corresponding methods in the Scribunto Ustring library.

string.byte
If the string is considered as an array of bytes, returns the byte values for,  , ···,. The default value for  is 1; the default value for  is. Identical to mw.ustring.byte.

string.char
Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the byte value equal to its corresponding argument.

See mw.ustring.char for a similar function that uses Unicode codepoints rather than byte values.

string.find
Looks for the first match of  in the string. If it finds a match, then  returns the offsets in   where this occurrence starts and ends; otherwise, it returns nil. If the pattern has captures, then in a successful match the captured values are also returned after the two indices.

A third, optional numerical argument  specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument  turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in   being considered "magic".

Note that if  is given, then   must be given as well.

See mw.ustring.find for a similar function extended as described in Ustring patterns and where the  offset is in characters rather than bytes.

string.format
Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string).

The format string uses a limited subset of the format specifiers:


 * Recognized flags are '-', '+', ' ', '#', and '0'.
 * Integer field widths up to 99 are supported. '*' is not supported.
 * Integer precisions up to 99 are supported. '*' is not supported.
 * Length modifiers are not supported.
 * Recognized conversion specifiers are 'c', 'd', 'i', 'o', 'u', 'x', 'X', 'e', 'E', 'f', 'g', 'G', 's', '%', and the non-standard 'q'.
 * Positional specifiers (e.g. "%2$s") are not supported.

The conversion specifier 'q' is like 's', but formats the string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written.

Conversion between strings and numbers is performed as specified in Data types; other types are not automatically converted to strings. Strings containing NUL characters (byte value 0) are not properly handled.

Identical to mw.ustring.format.

string.gmatch
Returns an iterator function that, each time it is called, returns the next captures from  over string. If  specifies no captures, then the whole match is produced in each call.

For this function, a ' ' at the start of a pattern is not magic, as this would prevent the iteration. It is treated as a literal character.

See mw.ustring.gmatch for a similar function for which the pattern is extended as described in Ustring patterns.

string.gsub
Returns a copy of  in which all (or the first , if given) occurrences of the   have been replaced by a replacement string specified by  , which can be a string, a table, or a function. also returns, as its second value, the total number of matches that occurred.

If  is a string, then its value is used for replacement. The character  works as an escape character: any sequence in   of the form  , with n between 1 and 9, stands for the value of the n-th captured substring. The sequence  stands for the whole match, and the sequence   stands for a single.

If  is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.

If  is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.

If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).

See mw.ustring.gsub for a similar function in which the pattern is extended as described in Ustring patterns.

string.len
Returns the length of the string, in bytes. Is not confused by ASCII NUL characters. Equivalent to.

See mw.ustring.len for a similar function using Unicode codepoints rather than bytes.

string.lower
Returns a copy of this string with all ASCII uppercase letters changed to lowercase. All other characters are left unchanged.

See mw.ustring.lower for a similar function in which all characters with uppercase to lowercase definitions in Unicode are converted.

string.match
Looks for the first match of  in the string. If it finds one, then  returns the captures from the pattern; otherwise it returns nil. If  specifies no captures, then the whole match is returned.

A third, optional numerical argument  specifies where to start the search; its default value is 1 and can be negative.

See mw.ustring.match for a similar function in which the pattern is extended as described in Ustring patterns and the  offset is in characters rather than bytes.

string.rep
Returns a string that is the concatenation of  copies of the string. Identical to mw.ustring.rep.

string.reverse
Returns a string that is the string  reversed (bytewise).

string.sub
Returns the substring of  that starts at   and continues until  ;   and   can be negative. If  is nil or omitted, it will continue until the end of the string.

In particular, the call  returns a prefix of   with length , and   returns a suffix of   with length.

See mw.ustring.sub for a similar function in which the offsets are characters rather than bytes.

string.upper
Returns a copy of this string with all ASCII lowercase letters changed to uppercase. All other characters are left unchanged.

See mw.ustring.upper for a similar function in which all characters with lowercase to uppercase definitions in Unicode are converted.

Patterns
Note that Lua's patterns are similar to regular expressions, but are not identical. In particular, note the following differences from regular expressions and PCRE:


 * The quoting character is percent, not backslash.
 * Dot always matches all characters, including newlines.
 * No case-insensitive mode.
 * No alternation (the  operator).
 * Quantifiers (, ,  , and  ) may only be applied to individual characters or character classes, not to capture groups.
 * The only non-greedy quantifier is, which is equivalent to PCRE's   quantifier.
 * No generalized finite quantifier (e.g. the  quantifier in PCRE).
 * The only zero-width assertions are,  , and the   "frontier" pattern; assertions such as PCRE's   or   are not present.
 * Patterns themselves do not recognize character escapes such as '\ddd'. However, since patterns are strings these sort of escapes may be used in the string literals used to create the pattern-string.

Also note that a pattern cannot contain embedded zero bytes (ASCII NUL, ). Use  instead.

Also see Ustring patterns for a similar pattern-matching scheme using Unicode characters.

Character class
A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:


 * x: (where x is not one of the magic characters ) represents the character x itself.
 *  : (a dot) represents all characters.
 *  : represents all ASCII letters.
 *  : represents all ASCII control characters.
 *  : represents all digits.
 *  : represents all ASCII lowercase letters.
 *  : represents all punctuation characters.
 *  : represents all ASCII space characters.
 *  : represents all ASCII uppercase letters.
 *  : represents all ASCII alphanumeric characters.
 *  : represents all hexadecimal digits.
 *  : represents ASCII NUL, the zero byte.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : All characters not in.
 *  : (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters. Any punctuation character (even the non magic) can be preceded by a ' ' when used to represent itself in a pattern.
 *  : represents the class which is the union of all characters in set. A range of characters can be specified by separating the end characters of the range with a ' '. All classes  described above can also be used as components in set. All other characters in set represent themselves. For example,   (or  ) represents all alphanumeric characters plus the underscore,   represents the octal digits, and   represents the octal digits plus the lowercase letters plus the ' ' character. The interaction between ranges and classes is not defined. Therefore, patterns like   or   have no meaning.
 *  : represents the complement of set, where set is interpreted as above.

Pattern items
A pattern item can be


 * a single character class, which matches any single character in the class;
 * a single character class followed by ' ', which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
 * a single character class followed by ' ', which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
 * a single character class followed by ' ', which also matches 0 or more repetitions of characters in the class. Unlike ' ', these repetition items will always match the shortest possible sequence;
 * a single character class followed by ' ', which matches 0 or 1 occurrence of a character in the class;
 * , for n between 1 and 9; such item matches a substring equal to the n-th captured string (see below);
 * , where x and y are two distinct characters; such item matches strings that start with x, end with y, and where the x and y are balanced. This means that, if one reads the string from left to right, counting +1 for an x and -1 for a y, the ending y is the first y where the count reaches 0. For instance, the item  matches expressions with balanced parentheses.


 * , a frontier pattern; such item matches an empty string at any position such that the next character belongs to set and the previous character does not belong to set. The set set is interpreted as previously described. The beginning and the end of the subject are handled as if they were the character '\0'. Note that frontier patterns were present but undocumented in Lua 5.1, and officially added to Lua in 5.2. The implementation in Lua 5.2.1 is unchanged from that in 5.1.0.

Pattern
A pattern is a sequence of pattern items.

A ' ' at the beginning of a pattern anchors the match at the beginning of the subject string. A ' ' at the end of a pattern anchors the match at the end of the subject string. At other positions, ' ' and ' ' have no special meaning and represent themselves.

Captures
A pattern can contain sub-patterns enclosed in parentheses; they describe captures. When a match succeeds, the substrings of the subject string that match captures are stored ("captured") for future use. Captures are numbered according to their left parentheses. For instance, in the pattern, the part of the string matching   is stored as the first capture (and therefore has number 1); the character matching   is captured with number 2, and the part matching   has number 3.

Capture references can appear in the pattern string itself, and refer back to text that was captured earlier in the match. For example,  will match any pair of identical lowercase letters, while   will match any 7-letter palindrome.

As a special case, the empty capture  captures the current string position (a number). For instance, if we apply the pattern  on the string , there will be two captures: 3 and 5.

Table library
Most functions in the table library assume that the table represents a sequence.

The functions,  , and   may be available but are deprecated. Use a for loop with pairs, a for loop with ipairs, and the length operator instead.

table.concat
Given an array where all elements are strings or numbers, returns.

The default value for  is the empty string, the default for   is 1, and the default for   is the length of the table. If  is greater than , returns the empty string.

table.insert
Inserts element  at position   in , shifting up other elements to open space, if necessary. The default value for  is the length of the table plus 1, so that a call   inserts   at the end of table.

Elements up to  are shifted; see Length operator for caveats if the table is not a sequence.

table.maxn
Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices.

To do this, it iterates over the whole table. This is roughly equivalent to

table.remove
Removes from  the element at position  , shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for  is the length of the table, so that a call   removes the last element of table.

Elements up to  are shifted; see Length operator for caveats if the table is not a sequence.

table.sort
Sorts table elements in a given order, in-place, from  to. If  is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that   will be true after the sort). If  is not given, then the standard Lua operator   is used instead.

The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.

Scribunto libraries
All Scribunto libraries are located in the table.

mw.addWarning
Adds a warning which is displayed above the preview when previewing an edit. is parsed as wikitext.

mw.allToString
Calls tostring on all arguments, then concatenates them with tabs as separators.

mw.clone
Creates a deep copy of a value. All tables (and their metatables) are reconstructed from scratch. Functions are still shared, however.

mw.getCurrentFrame
Returns the current frame object, typically the frame object from the most recent.

mw.incrementExpensiveFunctionCount
Adds one to the "expensive parser function" count, and throws an exception if it exceeds the limit (see ).

mw.isSubsting
Returns true if the current  is being substed, false otherwise. See Returning text above for discussion on differences when substing versus not substing.

mw.loadData
Sometimes a module needs large tables of data; for example, a general-purpose module to convert units of measure might need a large table of recognized units and their conversion factors. And sometimes these modules will be used many times in one page. Parsing the large data table for every  can use a significant amount of time. To avoid this issue,  is provided.

works like, with the following differences:


 * The loaded module is evaluated only once per page, rather than once per  call.
 * The loaded module is not recorded in.
 * The value returned from the loaded module must be a table. Other data types are not supported.
 * The returned table (and all subtables) may contain only booleans, numbers, strings, and other tables. Other data types, particularly functions, are not allowed.
 * The returned table (and all subtables) may not have a metatable.
 * All table keys must be booleans, numbers, or strings.
 * The table actually returned by  has metamethods that provide read-only access to the table returned by the module. Since it does not contain the data directly,   and   will work but other methods, including ,  , and the functions in the Table library, will not work correctly.

The hypothetical unit-conversion module mentioned above might store its code in "Module:Convert" and its data in "Module:Convert/data", and "Module:Convert" would use  to efficiently load the data.

mw.dumpObject
Serializes  to a human-readable representation, then returns the resulting string.

mw.log
Passes the arguments to mw.allToString, then appends the resulting string to the log buffer.

In the debug console, the function  is an alias for this function.

mw.logObject
Calls mw.dumpObject and appends the resulting string to the log buffer. If  is given, it will be added to the log buffer followed by an equals sign before the serialized string is appended (i.e. the logged text will be "prefix = object-string").

Frame object
The frame object is the interface to the parameters passed to, and to the parser.

Note that there is no frame library, and there is no global variable named. A frame object is typically obtained by being passed as a parameter to the function called by, and can also be obtained from.

frame.args
A table for accessing the arguments passed to the frame. For example, if a module is called from wikitext with

then  will return ,   will return  , and   (or  ) will return. It is also possible to iterate over arguments using  or. However, due to how Lua implements table iterators, iterating over arguments will return them in an unspecified order, and there's no way to know the original order as they appear in wikitext.

Note that values in this table are always strings;  may be used to convert them to numbers, if necessary. Keys, however, are numbers even if explicitly supplied in the invocation:  gives string values   and   indexed by numeric keys   and.

As in MediaWiki template invocations, named arguments will have leading and trailing whitespace removed from both the name and the value before they are passed to Lua, whereas unnamed arguments will not have whitespace stripped.

For performance reasons,  uses a metatable, rather than directly containing the arguments. Argument values are requested from MediaWiki on demand. This means that most other table methods will not work correctly, including,  , and the functions in the Table library.

If preprocessor syntax such as template invocations and triple-brace arguments are included within an argument to #invoke, they will not be expanded, after being passed to Lua, until their values are being requested in Lua. If certain special tags written in XML notation, such as,  ,   and  , are included as arguments to #invoke, then these tags will be converted to "strip markers" — special strings which begin with a delete character (ASCII 127), to be replaced with HTML after they are returned from #invoke.

frame:callParserFunction

 * Note the use of named arguments.

Call a parser function, returning an appropriate string. Whenever possible, native Lua functions or Scribunto library functions should be preferred to this interface.

The following calls are approximately equivalent to the indicated wikitext:

Note that, as with frame:expandTemplate, the function name and arguments are not preprocessed before being passed to the parser function.

frame:expandTemplate

 * Note the use of named arguments.

This is transclusion. The call

frame:expandTemplate{ title = 'template', args = { 'arg1', 'arg2', name = 'arg3' } }

does roughly the same thing from Lua that  does in wikitext. As in transclusion, if the passed title does not contain a namespace prefix it will be assumed to be in the Template: namespace.

Note that the title and arguments are not preprocessed before being passed into the template:

frame:extensionTag
This is equivalent to a call to frame:callParserFunction with function name  and with   prepended to.

frame:getParent
Called on the frame created by, returns the frame for the page that called. Called on that frame, returns nil.

For instance, if the template  contains the code , and a page transcludes that template and supplies arguments to it , calling   in Module:ModuleName will return.

frame:getTitle
Returns the title associated with the frame as a string. For the frame created by, this is the title of the module invoked.

frame:newChild

 * Note the use of named arguments.

Create a new Frame object that is a child of the current frame, with optional arguments and title.

This is mainly intended for use in the debug console for testing functions that would normally be called by. The number of frames that may be created at any one time is limited.

frame:preprocess
This expands wikitext in the context of the frame, i.e. templates, parser functions, and parameters such as  are expanded. Certain special tags written in XML-style notation, such as,  ,   and  , will be replaced with "strip markers" &mdash; special strings which begin with a delete character (ASCII 127), to be replaced with HTML after they are returned from.

If you are expanding a single template, use  instead of trying to construct a wikitext string to pass to this method. It's faster and less prone to error if the arguments contain pipe characters or other wikimarkup.

If you are expanding a single parser function, use  for the same reasons.

frame:getArgument
Gets an object for the specified argument, or nil if the argument is not provided.

The returned object has one method,, that returns the expanded wikitext for the argument.

frame:newParserValue
Returns an object with one method,, that returns the result of.

frame:newTemplateParserValue

 * Note the use of named arguments.

Returns an object with one method,, that returns the result of   called with the given arguments.

frame:argumentPairs
Same as. Included for backwards compatibility.

mw.hash.hashValue
Hashes a string value with the specified algorithm. Valid algorithms may be fetched using mw.hash.listAlgorithms.

mw.hash.listAlgorithms
Returns a list of supported hashing algorithms, for use in mw.hash.hashValue.

HTML library
is a fluent interface for building complex HTML from Lua. A mw.html object can be created using.

Functions documented as  are available on the global   table; functions documented as   and   are methods of an mw.html object (see  ).

A basic example could look like this:

mw.html.create
Creates a new mw.html object containing a  html element. You can also pass an empty string or nil as  in order to create an empty mw.html object.

can be a table with the following keys:


 * : Force the current tag to be self-closing, even if mw.html doesn't recognize it as self-closing
 * : Parent of the current mw.html instance (intended for internal usage)

mw.html:node
Appends a child mw.html node to the current mw.html instance. If a nil parameter is passed, this is a no-op. A node is a string representation of an html element.

mw.html:wikitext
Appends an undetermined number of wikitext strings to the mw.html object.

Note that this stops at the first nil item.

mw.html:newline
Appends a newline to the mw.html object.

mw.html:tag
Appends a new child node with the given  to the builder, and returns a mw.html instance representing that new node. The  parameter is identical to that of

mw.html:attr
Set an HTML attribute with the given  and   on the node. Alternatively a table holding name->value pairs of attributes to set can be passed. In the first form, a value of nil causes any attribute with the given name to be unset if it was previously set.

mw.html:getAttr
Get the value of a html attribute previously set using  with the given.

mw.html:addClass
Adds a class name to the node's class attribute. If a nil parameter is passed, this is a no-op.

mw.html:css
Set a CSS property with the given  and   on the node. Alternatively a table holding name->value pairs of properties to set can be passed. In the first form, a value of nil causes any property with the given name to be unset if it was previously set.

mw.html:cssText
Add some raw  to the node's style attribute. If a nil parameter is passed, this is a no-op.

mw.html:done
Returns the parent node under which the current node was created. Like jQuery.end, this is a convenience function to allow the construction of several child nodes to be chained together into a single statement.

mw.html:allDone
Like, but traverses all the way to the root node of the tree and returns it.

Language library
Language codes are described at language code. Many of MediaWiki's language codes are similar to IETF language tags, but not all MediaWiki language codes are valid IETF tags or vice versa.

Functions documented as  are available on the global   table; functions documented as   and   are methods of a language object (see   or  ).

mw.language.fetchLanguageName
The full name of the language for the given language code: native name (language autonym) by default, name translated in target language if a value is given for.

mw.language.fetchLanguageNames
Fetch the list of languages known to MediaWiki, returning a table mapping language code to language name.

By default the name returned is the language autonym; passing a language code for  returns all names in that language.

By default, only language names known to MediaWiki are returned; passing  for   will return all available languages (e.g. from Extension:CLDR), while passing   will include only languages having customized messages included with MediaWiki core or enabled extensions. To explicitly select the default,  may be passed.

mw.language.getContentLanguage
Returns a new language object for the wiki's default content language.

mw.language.getFallbacksFor
Returns a list of MediaWiki's fallback language codes for the specified code.

mw.language.isKnownLanguageTag
Returns true if a language code is known to MediaWiki.

A language code is "known" if it is a "valid built-in code" (i.e. it returns true for ) and returns a non-empty string for.

mw.language.isSupportedLanguage
Checks whether any localisation is available for that language code in MediaWiki.

A language code is "supported" if it is a "valid" code (returns true for ), contains no uppercase letters, and has a message file in the currently-running version of MediaWiki.

It is possible for a language code to be "supported" but not "known" (i.e. returning true for ). Also note that certain codes are "supported" despite  returning false.

mw.language.isValidBuiltInCode
Returns true if a language code is of a valid form for the purposes of internal customisation of MediaWiki.

The code may not actually correspond to any known language.

A language code is a "valid built-in code" if it is a "valid" code (i.e. it returns true for ); consists of only ASCII letters, numbers, and hyphens; and is at least two characters long.

Note that some codes are "supported" (i.e. returning true from ) even though this function returns false.

mw.language.isValidCode
Returns true if a language code string is of a valid form, whether or not it exists. This includes codes which are used solely for customisation via the MediaWiki namespace.

The code may not actually correspond to any known language.

A language code is valid if it does not contain certain unsafe characters (colons, single- or double-quotes, slashs, backslashs, angle brackets, ampersands, or ASCII NULs) and is otherwise allowed in a page title.

mw.language.new
Creates a new language object. Language objects do not have any publicly accessible properties, but they do have several methods, which are documented below.

There is a limit on the number of distinct language codes that may be used on a page. Exceeding this limit will result in errors.

mw.language:getCode
Returns the language code for this language object.

mw.language:getFallbackLanguages
Returns a list of MediaWiki's fallback language codes for this language object. Equivalent to.

mw.language:isRTL
Returns true if the language is written right-to-left, false if it is written left-to-right.

mw.language:lc
Converts the string to lowercase, honoring any special rules for the given language.

When the Ustring library is loaded, the mw.ustring.lower function is implemented as a call to.

mw.language:lcfirst
Converts the first character of the string to lowercase, as with lang:lc.

mw.language:uc
Converts the string to uppercase, honoring any special rules for the given language.

When the Ustring library is loaded, the mw.ustring.upper function is implemented as a call to.

mw.language:ucfirst
Converts the first character of the string to uppercase, as with lang:uc.

mw.language:caseFold
Converts the string to a representation appropriate for case-insensitive comparison. Note that the result may not make any sense when displayed.

mw.language:formatNum
Formats a number with grouping and decimal separators appropriate for the given language. Given 123456.78, this may produce "123,456.78", "123.456,78", or even something like "١٢٣٬٤٥٦٫٧٨" depending on the language and wiki configuration.

The  is a table of options, which can be:


 * : Set true to omit grouping separators and use a dot as the decimal separator. Digit transformation may still occur, which may include transforming the decimal separator.

mw.language:formatDate
Formats a date according to the given format string. If  is omitted, the default is the current time. The value for  must be a boolean or nil; if true, the time is formatted in the wiki's local time rather than in UTC.

The format string and supported values for  are identical to those for the #time parser function from Extension:ParserFunctions. Note however that backslashes may need to be doubled in a Lua string literal, since Lua also uses backslash as an escape character while wikitext does not:

mw.language:formatDuration
Breaks a duration in seconds into more human-readable units, e.g. 12345 to 3 hours, 25 minutes and 45 seconds, returning the result as a string.

, if given, is a table with values naming the interval units to use in the response. These include 'millennia', 'centuries', 'decades', 'years', 'weeks', 'days', 'hours', 'minutes', and 'seconds'.

mw.language:parseFormattedNumber
This takes a number as formatted by lang:formatNum and returns the actual number. In other words, this is basically a language-aware version of.

mw.language:convertPlural
This chooses the appropriate grammatical form from  (which must be a sequence table) or   based on the number. For example, in English you might use  or   to generate grammatically-correct text whether there is only 1 sock or 200 socks.

The necessary values for the sequence are language-dependent, see localization of magic words and translatewiki's FAQ on PLURAL for some details.

mw.language:convertGrammar

 * Note the different parameter order between the two aliases.  matches the order of the method of the same name on MediaWiki's Language object, while   matches the order of the parser function of the same name, documented at Special:MyLanguage/Help:Magic words.

This chooses the appropriate inflected form of  for the given inflection code.

The possible values for  and   are language-dependent, see Special:MyLanguage/Help:Magic words and translatewiki:Grammar for some details.

mw.language:gender
Chooses the string corresponding to the gender of, which may be "male", "female", or a registered user name.

mw.language:getArrow
Returns a Unicode arrow character corresponding to :


 * forwards: Either "→" or "←" depending on the directionality of the language.
 * backwards: Either "←" or "→" depending on the directionality of the language.
 * left: "←"
 * right: "→"
 * up: "↑"
 * down: "↓"

mw.language:getDir
Returns "ltr" or "rtl", depending on the directionality of the language.

mw.language:getDirMark
Returns a string containing either U+200E (the left-to-right mark) or U+200F (the right-to-left mark), depending on the directionality of the language and whether  is a true or false value.

mw.language:getDirMarkEntity
Returns "&amp;lrm;" or "&amp;rlm;", depending on the directionality of the language and whether  is a true or false value.

mw.language:getDurationIntervals
Breaks a duration in seconds into more human-readable units, e.g. 12345 to 3 hours, 25 minutes and 45 seconds, returning the result as a table mapping unit names to numbers.

, if given, is a table with values naming the interval units to use in the response. These include 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', and 'seconds'.

Message library
This library is an interface to the localisation messages and the MediaWiki: namespace.

Functions documented as  are available on the global   table; functions documented as   and   are methods of a message object (see  ).

mw.message.new
Creates a new message object for the given message.

The message object has no properties, but has several methods documented below.

mw.message.newFallbackSequence
Creates a new message object for the given messages (the first one that exists will be used).

The message object has no properties, but has several methods documented below.

mw.message.newRawMessage
Creates a new message object, using the given text directly rather than looking up an internationalized message. The remaining parameters are passed to the new object's  method.

The message object has no properties, but has several methods documented below.

mw.message.rawParam
Wraps the value so that it will not be parsed as wikitext by.

mw.message.numParam
Wraps the value so that it will automatically be formatted as by. Note this does not depend on the Language library actually being available.

mw.message.getDefaultLanguage
Returns a Language object for the default language.

mw.message:params
Add parameters to the message, which may be passed as individual arguments or as a sequence table. Parameters must be numbers, strings, or the special values returned by mw.message.numParam or mw.message.rawParam. If a sequence table is used, parameters must be directly present in the table; references using the __index metamethod will not work.

Returns the  object, to allow for call chaining.

mw.message:rawParams
Like params, but has the effect of passing all the parameters through mw.message.rawParam first.

Returns the  object, to allow for call chaining.

mw.message:numParams
Like params, but has the effect of passing all the parameters through mw.message.numParam first.

Returns the  object, to allow for call chaining.

mw.message:inLanguage
Specifies the language to use when processing the message. may be a string or a table with a  method (i.e. a Language object).

The default language is the one returned by.

Returns the  object, to allow for call chaining.

mw.message:useDatabase
Specifies whether to look up messages in the MediaWiki: namespace (i.e. look in the database), or just use the default messages distributed with MediaWiki.

The default is true.

Returns the  object, to allow for call chaining.

mw.message:plain
Substitutes the parameters and returns the message wikitext as-is. Template calls and parser functions are intact.

mw.message:exists
Returns a boolean indicating whether the message key exists.

mw.message:isBlank
Returns a boolean indicating whether the message key has content. Returns true if the message key does not exist or the message is the empty string.

mw.message:isDisabled
Returns a boolean indicating whether the message key is disabled. Returns true if the message key does not exist or if the message is the empty string or the string "-".

mw.site.currentVersion
A string holding the current version of MediaWiki.

mw.site.scriptPath
The value of.

mw.site.server
The value of.

mw.site.siteName
The value of.

mw.site.stylePath
The value of.

mw.site.namespaces
Table holding data for all namespaces, indexed by number.

The data available is:


 * id: Namespace number.
 * name: Local namespace name.
 * canonicalName: Canonical namespace name.
 * displayName: Set on namespace 0, the name to be used for display (since the name is often the empty string).
 * hasSubpages: Whether subpages are enabled for the namespace.
 * hasGenderDistinction: Whether the namespace has different aliases for different genders.
 * isCapitalized: Whether the first letter of pages in the namespace is capitalized.
 * isContent: Whether this is a content namespace.
 * isIncludable: Whether pages in the namespace can be transcluded.
 * isMovable: Whether pages in the namespace can be moved.
 * isSubject: Whether this is a subject namespace.
 * isTalk: Whether this is a talk namespace.
 * defaultContentModel: The default content model for the namespace, as a string.
 * aliases: List of aliases for the namespace.
 * subject: Reference to the corresponding subject namespace's data.
 * talk: Reference to the corresponding talk namespace's data.
 * associated: Reference to the associated namespace's data.

A metatable is also set that allows for looking up namespaces by name (localized or canonical). For example, both  and   will return information about the Project namespace.

mw.site.contentNamespaces
Table holding just the content namespaces, indexed by number. See mw.site.namespaces for details.

mw.site.subjectNamespaces
Table holding just the subject namespaces, indexed by number. See mw.site.namespaces for details.

mw.site.talkNamespaces
Table holding just the talk namespaces, indexed by number. See mw.site.namespaces for details.

mw.site.stats
Table holding site statistics. Available statistics are:


 * pages: Number of pages in the wiki.
 * articles: Number of articles in the wiki.
 * files: Number of files in the wiki.
 * edits: Number of edits in the wiki.
 * users: Number of users in the wiki.
 * activeUsers: Number of active users in the wiki.
 * admins: Number of users in group 'sysop' in the wiki.

mw.site.stats.pagesInCategory


Gets statistics about the category. If  is unspecified, nil, or "*", returns a table with the following properties:


 * all: Total pages, files, and subcategories.
 * subcats: Number of subcategories.
 * files: Number of files.
 * pages: Number of pages.

If  is one of the above keys, just the corresponding value is returned instead.

Each new category queried will increment the expensive function count.

mw.site.stats.pagesInNamespace
Returns the number of pages in the given namespace (specify by number).

mw.site.stats.usersInGroup
Returns the number of users in the given group.

mw.site.interwikiMap
Returns a table holding data about available interwiki prefixes. If  is the string "local", then only data for local interwiki prefixes is returned. If  is the string "!local", then only data for non-local prefixes is returned. If no filter is specified, data for all prefixes is returned. A "local" prefix in this context is one that is for the same project. For example, on the English Wikipedia, other-language Wikipedias are considered local, while Wiktionary and such are not.

Keys in the table returned by this function are interwiki prefixes, and the values are subtables with the following properties:


 * prefix - the interwiki prefix.
 * url - the URL that the interwiki points to. The page name is represented by the parameter $1.
 * isProtocolRelative - a boolean showing whether the URL is protocol-relative.
 * isLocal - whether the URL is for a site in the current project.
 * isCurrentWiki - whether the URL is for the current wiki.
 * isTranscludable - whether pages using this interwiki prefix are transcludable. This requires scary transclusion, which is disabled on Wikimedia wikis.
 * isExtraLanguageLink - whether the interwiki is listed in.
 * displayText - for links listed in $wgExtraInterlanguageLinkPrefixes, this is the display text shown for the interlanguage link. Nil if not specified.
 * tooltip - for links listed in $wgExtraInterlanguageLinkPrefixes, this is the tooltip text shown when users hover over the interlanguage link. Nil if not specified.

Text library
The text library provides some common text processing functions missing from the String library and the Ustring library. These functions are safe for use with UTF-8 strings.

mw.text.decode
Replaces HTML entities in the string with the corresponding characters.

If boolean  is omitted or false, the only named entities recognized are '&amp;lt;', '&amp;gt;', '&amp;amp;', '&amp;quot;', and '&amp;nbsp;'. Otherwise, the list of HTML5 named entities to recognize is loaded from PHP's function.

mw.text.encode
Replaces characters in a string with HTML entities. Characters '<', '>', '&', '"', and the non-breaking space are replaced with the appropriate named entities; all others are replaced with numeric entities.

If  is supplied, it should be a string as appropriate to go inside brackets in a Ustring pattern, i.e. the "set" in. The default charset is  (the space at the end is the non-breaking space, U+00A0).

mw.text.jsonDecode
Decodes a JSON string. is 0 or a combination (use ) of the flags   and.

Normally JSON's zero-based arrays are renumbered to Lua one-based sequence tables; to prevent this, pass.

To relax certain requirements in JSON, such as no terminal comma in arrays or objects, pass. This is not recommended.

Limitations:


 * Decoded JSON arrays may not be Lua sequences if the array contains null values.
 * JSON objects will drop keys having null values.
 * It is not possible to directly tell whether the input was a JSON array or a JSON object with sequential integer keys.
 * A JSON object having sequential integer keys beginning with 1 will decode to the same table structure as a JSON array with the same values, despite these not being at all equivalent, unless  is used.

mw.text.jsonEncode
Encode a JSON string. Errors are raised if the passed value cannot be encoded in JSON. is 0 or a combination (use ) of the flags   and.

Normally Lua one-based sequence tables are encoded as JSON zero-based arrays; when  is set in , zero-based sequence tables are encoded as JSON arrays.

Limitations:


 * Empty tables are always encoded as empty arrays, not empty objects.
 * Sequence tables cannot be encoded as JSON objects without adding a "dummy" element.
 * To produce objects or arrays with nil values, a tricky implementation of the  metamethod is required.
 * A Lua table having sequential integer keys beginning with 0 will encode as a JSON array, the same as a Lua table having integer keys beginning with 1, unless  is used.
 * When both a number and the string representation of that number are used as keys in the same table, behavior is unspecified.

mw.text.killMarkers
Removes all MediaWiki strip markers from a string.

mw.text.listToText
Joins a list, prose-style. In other words, it's like  but with a different separator before the final item.

The default separator is taken from MediaWiki:comma-separator in the wiki's content language, and the default conjunction is MediaWiki:and concatenated with MediaWiki:word-separator.

Examples, using the default values for the messages:

mw.text.nowiki
Replaces various characters in the string with HTML entities to prevent their interpretation as wikitext. This includes:


 * The following characters: '"', '&', "'", '<', '=', '>', '[', ']', '{', '|', '}'
 * The following characters at the start of the string or immediately after a newline: '#', '*', ':', ';', space, tab ('\t')
 * Blank lines will have one of the associated newline or carriage return characters escaped
 * "" at the start of the string or immediately after a newline will have the first '-' escaped
 * "__" will have one underscore escaped
 * "://" will have the colon escaped
 * A whitespace character following "ISBN", "RFC", or "PMID" will be escaped

mw.text.split
Splits the string into substrings at boundaries matching the Ustring pattern. If  is specified and true,   will be interpreted as a literal string rather than as a Lua pattern (just as with the parameter of the same name for  ). Returns a table containing the substrings.

For example,  would return a table.

If  matches the empty string,   will be split into individual characters.

mw.text.gsplit
Returns an iterator function that will iterate over the substrings that would be returned by the equivalent call to.

mw.text.tag

 * Note the use of named arguments.

Generates an HTML-style tag for.

If  is given, it must be a table with string keys. String and number values are used as the value of the attribute; boolean true results in the key being output as an HTML5 valueless parameter; boolean false skips the key entirely; and anything else is an error.

If  is not given (or is nil), only the opening tag is returned. If  is boolean false, a self-closed tag is returned. Otherwise it must be a string or number, in which case that content is enclosed in the constructed opening and closing tag. Note the content is not automatically HTML-encoded; use mw.text.encode if needed.

For properly returning extension tags such as, use frame:extensionTag instead.

mw.text.trim
Remove whitespace or other characters from the beginning and end of a string.

If  is supplied, it should be a string as appropriate to go inside brackets in a Ustring pattern, i.e. the "set" in. The default charset is ASCII whitespace,.

mw.text.truncate
Truncates  to the specified length, adding   if truncation was performed. If length is positive, the end of the string will be truncated; if negative, the beginning will be removed. If  is given and true, the resulting string including ellipsis will not be longer than the specified length.

The default value for  is taken from MediaWiki:ellipsis in the wiki's content language.

Examples, using the default "..." ellipsis:

mw.text.unstripNoWiki
Replaces MediaWiki &lt;nowiki&gt; strip markers with the corresponding text. Other types of strip markers are not changed.

mw.text.unstrip
Equivalent to.

This no longer reveals the HTML behind special page transclusion, &lt;ref&gt; tags, and so on as it did in earlier versions of Scribunto.

mw.title.equals
Test for whether two titles are equal. Note that fragments are ignored in the comparison.

mw.title.compare
Returns -1, 0, or 1 to indicate whether the title  is less than, equal to, or greater than title.

This compares titles by interwiki prefix (if any) as strings, then by namespace number, then by the unprefixed title text as a string. These string comparisons use Lua's standard  operator.

mw.title.getCurrentTitle
Returns the title object for the current page.

mw.title.new


Creates a new title object.

If a number  is given, an object is created for the title with that page_id. The title referenced will be counted as linked from the current page. If the page_id does not exist, returns nil. The expensive function count will be incremented if the title object created is not for a title that has already been loaded.

If a string  is given instead, an object is created for that title (even if the page does not exist). If the text string does not specify a namespace,  (which may be any key found in  ) will be used. If the text is not a valid title, nil is returned.

mw.title.makeTitle
Creates a title object with title  in namespace , optionally with the specified   and   prefix. may be any key found in. If the resulting title is not valid, returns nil.

Note that, unlike, this method will always apply the specified namespace. For example,  will create an object for the page Template:Module:Foo, while   will create an object for the page Module:Foo.

Title objects
A title object has a number of properties and methods. Most of the properties are read-only.

Note that fields ending with  return titles as string values whereas the fields ending with   return title objects.


 * id: The page_id. 0 if the page does not exist..
 * interwiki: The interwiki prefix, or the empty string if none.
 * namespace: The namespace number.
 * fragment: The fragment, or the empty string. May be assigned.
 * nsText: The text of the namespace for the page.
 * subjectNsText: The text of the subject namespace for the page.
 * text: The title of the page, without the namespace or interwiki prefixes.
 * prefixedText: The title of the page, with the namespace and interwiki prefixes.
 * fullText: The title of the page, with the namespace and interwiki prefixes and the fragment. Interwiki is not returned if equal to the current.
 * rootText: If this is a subpage, the title of the root page without prefixes. Otherwise, the same as.
 * baseText: If this is a subpage, the title of the page it is a subpage of without prefixes. Otherwise, the same as.
 * subpageText: If this is a subpage, just the subpage name. Otherwise, the same as.
 * canTalk: Whether the page for this title could have a talk page.
 * exists: Whether the page exists. Alias for file.exists for Media-namespace titles. For File-namespace titles this checks the existence of the file description page, not the file itself..
 * file, fileExists: See below.
 * isContentPage: Whether this title is in a content namespace.
 * isExternal: Whether this title has an interwiki prefix.
 * isLocal: Whether this title is in this project. For example, on the English Wikipedia, any other Wikipedia is considered "local" while Wiktionary and such are not.
 * isRedirect: Whether this is the title for a page that is a redirect..
 * isSpecialPage: Whether this is the title for a possible special page (i.e. a page in the Special: namespace).
 * isSubpage: Whether this title is a subpage of some other title.
 * isTalkPage: Whether this is a title for a talk page.
 * isSubpageOf( title2 ): Whether this title is a subpage of the given title.
 * inNamespace( ns ): Whether this title is in the given namespace. Namespaces may be specified by anything that is a key found in.
 * inNamespaces( ... ): Whether this title is in any of the given namespaces. Namespaces may be specified by anything that is a key found in.
 * hasSubjectNamespace( ns ): Whether this title's subject namespace is in the given namespace. Namespaces may be specified by anything that is a key found in.
 * contentModel: The content model for this title, as a string..
 * basePageTitle: The same as.
 * rootPageTitle: The same as.
 * talkPageTitle: The same as, or nil if this title cannot have a talk page.
 * subjectPageTitle: The same as.
 * redirectTarget: Returns a title object of the target of the redirect page if the page is a redirect and the page exists, returns false otherwise.
 * protectionLevels: The page's protection levels. This is a table with keys corresponding to each action (e.g., "edit" and "move"). The table values are arrays, the first item of which is a string containing the protection level. If the page is unprotected, either the table values or the array items will be nil..
 * subPageTitle( text ): The same as.
 * partialUrl: Returns  encoded as it would be in a URL.
 * fullUrl( query, proto ): Returns the full URL (with optional query table/string) for this title.  may be specified to control the scheme of the resulting url: "http", "https", "relative" (the default), or "canonical".
 * localUrl( query ): Returns the local URL (with optional query table/string) for this title.
 * canonicalUrl( query ): Returns the canonical URL (with optional query table/string) for this title.
 * getContent: Returns the (unparsed) content of the page, or nil if there is no page. The page will be recorded as a transclusion.

Title objects may be compared using relational operators. will return.

Since people find the fact surprising, note that accessing any expensive field on a title object records a "link" to the page (as shown on Special:WhatLinksHere, for example). Using the title object's  method or accessing the   field records it as a "", and accessing the title object's   or   fields records it as a "".

File metadata
Title objects representing a page in the File or Media namespace will have a property called. This is a table, structured as follows:


 * exists: Whether the file exists. It will be recorded as an image usage. The  property on a Title object exists for backwards compatibility reasons and is an alias for this property. If this is false, all other file properties will be nil.
 * width: The width of the file. If the file contains multiple pages, this is the width of the first page.
 * height: The height of the file. If the file contains multiple pages, this is the height of the first page.
 * pages: If the file format supports multiple pages, this is a table containing tables for each page of the file; otherwise, it is nil. The # operator can be used to get the number of pages in the file. Each individual page table contains a width and height property.
 * size: The size of the file in bytes.
 * mimeType: The MIME type of the file.

Expensive properties
The properties id, isRedirect, exists, and contentModel require fetching data about the title from the database. For this reason, the expensive function count is incremented the first time one of them is accessed for a page other than the current page. Subsequent accesses of any of these properties for that page will not increment the expensive function count again.

Other properties marked as expensive will always increment the expensive function count the first time they are accessed for a page other than the current page.

mw.uri.encode
Percent-encodes the string. The default type,, encodes spaces using '+' for use in query strings;   encodes spaces as %20; and   encodes spaces as '_'.

Note that the "WIKI" format is not entirely reversible, as both spaces and underscores are encoded as '_'.

mw.uri.decode
Percent-decodes the string. The default type,, decodes '+' to space;   does not perform any extra decoding; and   decodes '_' to space.

mw.uri.anchorEncode
Encodes a string for use in a MediaWiki URI fragment.

mw.uri.buildQueryString
Encodes a table as a URI query string. Keys should be strings; values may be strings or numbers, sequence tables, or boolean false.

mw.uri.parseQueryString
Decodes the query string  to a table. Keys in the string without values will have a value of false; keys repeated multiple times will have sequence tables as values; and others will have strings as values.

The optional numerical arguments  and   can be used to specify a substring of   to be parsed, rather than the entire string. is the position of the first character of the substring, and defaults to 1. is the position of the last character of the substring, and defaults to the length of the string. Both  and   can be negative, as in string.sub.

mw.uri.canonicalUrl
Returns a URI object for the canonical URL for a page, with optional query string/table.

mw.uri.fullUrl
Returns a URI object for the full URL for a page, with optional query string/table.

mw.uri.localUrl
Returns a URI object for the local URL for a page, with optional query string/table.

mw.uri.new
Constructs a new URI object for the passed string or table. See the description of URI objects for the possible fields for the table.

mw.uri.validate
Validates the passed table (or URI object). Returns a boolean indicating whether the table was valid, and on failure a string explaining what problems were found.

URI object
The URI object has the following fields, some or all of which may be nil:


 * protocol: String protocol/scheme
 * user: String user
 * password: String password
 * host: String host name
 * port: Integer port
 * path: String path
 * query: A table, as from mw.uri.parseQueryString
 * fragment: String fragment.

The following properties are also available:
 * userInfo: String user and password
 * hostPort: String host and port
 * authority: String user, password, host, and port
 * queryString: String version of the query table
 * relativePath: String path, query string, and fragment

will give the URI string.

Methods of the URI object are:

mw.uri:parse
Parses a string into the current URI object. Any fields specified in the string will be replaced in the current object; fields not specified will keep their old values.

mw.uri:clone
Makes a copy of the URI object.

mw.uri:extend
Merges the parameters table into the object's query table.

Ustring library
The ustring library is intended to be a direct reimplementation of the standard String library, except that the methods operate on characters in UTF-8 encoded strings rather than bytes.

Most functions will raise an error if the string is not valid UTF-8; exceptions are noted.

mw.ustring.maxPatternLength
The maximum allowed length of a pattern, in bytes.

mw.ustring.maxStringLength
The maximum allowed length of a string, in bytes.

mw.ustring.byte
Returns individual bytes; identical to string.byte.

mw.ustring.byteoffset
Returns the byte offset of a character in the string. The default for both  and   is 1. may be negative, in which case it counts from the end of the string.

The character at  == 1 is the first character starting at or after byte  ; the character at   == 0 is the first character starting at or before byte. Note this may be the same character. Greater or lesser values of  are calculated relative to these.

mw.ustring.char
Much like string.char, except that the integers are Unicode codepoints rather than byte values.

mw.ustring.codepoint
Much like string.byte, except that the return values are codepoints and the offsets are characters rather than bytes.

mw.ustring.find
Much like string.find, except that the pattern is extended as described in Ustring patterns and the  offset is in characters rather than bytes.

mw.ustring.format
Identical to string.format. Widths and precisions for strings are expressed in bytes, not codepoints.

mw.ustring.gcodepoint
Returns three values for iterating over the codepoints in the string. defaults to 1, and  to -1. This is intended for use in the iterator form of :

mw.ustring.gmatch
Much like string.gmatch, except that the pattern is extended as described in Ustring patterns.

mw.ustring.gsub
Much like string.gsub, except that the pattern is extended as described in Ustring patterns.

mw.ustring.isutf8
Returns true if the string is valid UTF-8, false if not.

mw.ustring.len
Returns the length of the string in codepoints, or nil if the string is not valid UTF-8.

See string.len for a similar function that uses byte length rather than codepoints.

mw.ustring.lower
Much like string.lower, except that all characters with lowercase to uppercase definitions in Unicode are converted.

If the Language library is also loaded, this will instead call lc on the default language object.

mw.ustring.match
Much like string.match, except that the pattern is extended as described in Ustring patterns and the  offset is in characters rather than bytes.

mw.ustring.rep
Identical to string.rep.

mw.ustring.sub
Much like string.sub, except that the offsets are characters rather than bytes.

mw.ustring.toNFC
Converts the string to Normalization Form C. Returns nil if the string is not valid UTF-8.

mw.ustring.toNFD
Converts the string to Normalization Form D. Returns nil if the string is not valid UTF-8.

mw.ustring.upper
Much like string.upper, except that all characters with uppercase to lowercase definitions in Unicode are converted.

If the Language library is also loaded, this will instead call uc on the default language object.

Ustring patterns
Patterns in the ustring functions use the same syntax as the String library patterns. The major difference is that the character classes are redefined in terms of Unicode character properties:


 *  : represents all characters with General Category "Letter".
 *  : represents all characters with General Category "Control".
 *  : represents all characters with General Category "Number, decimal digit".
 *  : represents all characters with General Category "Lowercase Letter".
 *  : represents all characters with General Category "Punctuation".
 *  : represents all characters with General Category "Separator", plus tab, linefeed, carriage return, vertical tab, and form feed.
 *  : represents all characters with General Category "Uppercase Letter".
 *  : represents all characters with General Category "Letter" or "Decimal Number".
 *  : adds fullwidth character versions of the hex digits.

Like in String library patterns,  ,  ,  ,  ,  ,  ,    here represent the complementary set ("all characters without given General Category").

In all cases, characters are interpreted as Unicode characters instead of bytes, so ranges such as, patterns such as  , and quantifiers applied to multibyte characters will work correctly. Empty captures will capture the position in code points rather than bytes.

Loadable libraries
These libraries are not included by default, but if needed may be loaded using.

bit32
This emulation of the Lua 5.2  library may be loaded using

bit32 = require( 'bit32' )

The bit32 library provides bitwise operations on unsigned 32-bit integers. Input numbers are truncated to integers (in an unspecified manner) and reduced modulo 232 so the value is in the range 0 to 232−1; return values are also in this range.

When bits are numbered (as in bit32.extract), 0 is the least-significant bit (the one with value 20) and 31 is the most-significant (the one with value 231).

bit32.band
Returns the bitwise AND of its arguments: the result has a bit set only if that bit is set in all of the arguments.

If given zero arguments, the result has all bits set.

bit32.bnot
Returns the bitwise complement of.

bit32.bor
Returns the bitwise OR of its arguments: the result has a bit set if that bit is set in any of the arguments.

If given zero arguments, the result has all bits clear.

bit32.btest
Equivalent to

bit32.bxor
Returns the bitwise XOR of its arguments: the result has a bit set if that bit is set in an odd number of the arguments.

If given zero arguments, the result has all bits clear.

bit32.extract
Extracts  bits from , starting with bit. Accessing bits outside of the range 0 to 31 is an error.

If not specified, the default for  is 1.

bit32.replace
Replaces  bits in , starting with bit  , with the low   bits from. Accessing bits outside of the range 0 to 31 is an error.

If not specified, the default for  is 1.

bit32.lshift
Returns the number  shifted   bits to the left. This is a logical shift: inserted bits are 0. This is generally equivalent to multiplying by 2undefined.

Note that a displacement over 31 will result in 0.

bit32.rshift
Returns the number  shifted   bits to the right. This is a logical shift: inserted bits are 0. This is generally equivalent to dividing by 2undefined.

Note that a displacement over 31 will result in 0.

bit32.arshift
Returns the number  shifted   bits to the right. This is an arithmetic shift: if  is positive, the inserted bits will be the same as bit 31 in the original number.

Note that a displacement over 31 will result in 0 or 4294967295.

bit32.lrotate
Returns the number  rotated   bits to the left.

Note that rotations are equivalent modulo 32: a rotation of 32 is the same as a rotation of 0, 33 is the same as 1, and so on.

bit32.rrotate
Returns the number  rotated   bits to the right.

Note that rotations are equivalent modulo 32: a rotation of 32 is the same as a rotation of 0, 33 is the same as 1, and so on.

libraryUtil
This library contains methods useful when implementing Scribunto libraries. It may be loaded using

libraryUtil = require( 'libraryUtil' )

libraryUtil.checkType
Raises an error if  does not match. In addition, no error will be raised if  is nil and   is true.

is the name of the calling function, and  is the position of the argument in the argument list. These are used in formatting the error message.

libraryUtil.checkTypeMulti
Raises an error if  does not match any of the strings in the array.

This is for arguments that have more than one valid type.

libraryUtil.checkTypeForIndex
Raises an error if  does not match.

This is intended for use in implementing a  metamethod.

libraryUtil.checkTypeForNamedArg
Raises an error if  does not match. In addition, no error will be raised if  is nil and   is true.

This is intended to be used as an equivalent to  in methods called using Lua's "named argument" syntax,.

libraryUtil.makeCheckSelfFunction
This is intended for use in implementing "methods" on object tables that are intended to be called with the  syntax. It returns a function that should be called at the top of these methods with the  argument and the method name, which will raise an error if that   object is not.

This function will generally be used in a library's constructor function, something like this:

luabit
The luabit library modules "bit" and "hex" may be loaded using

bit = require( 'luabit.bit' ) hex = require( 'luabit.hex' )

Note that the bit32 library contains the same operations as "luabit.bit", and the operations in "luabit.hex" may be performed using  and.

The luabit module "noki" is not available, as it is entirely useless in Scribunto. The luabit module "utf8" is also not available, as it was considered redundant to the Ustring library.

ustring
The pure-Lua backend to the Ustring library may be loaded using

ustring = require( 'ustring' )

In all cases the Ustring library should be used instead, as that replaces many of the slower and more memory-intensive operations with callbacks into PHP code.

Extension libraries
Some MediaWiki extensions provide additional Scribunto libraries. These are also located in the table, usually in the table  , however, they are only present when certain extensions are installed (in addition to the Scribunto extension itself).

Such extensions use Scribunto provided hooks:
 * ScribuntoExternalLibraries
 * ScribuntoExternalLibraryPaths

Writing Scribunto libraries provides information on how such libraries can be developed to provide Lua interfaces for Mediawiki extensions.

The following libraries are planned, or are in Gerrit pending review.


 * (none at this time)

mw.wikibase
Wikibase Client provides access to localizable structured data. See Extension:Wikibase Client/Lua. This is supported by Wikidata.

mw.wikibase.lexeme
WikibaseLexeme provides access to Wikibase Lexeme entities. This is supported by Wikidata:Lexicographical data.

mw.wikibase.mediainfo
WikibaseMediaInfo provides access to Wikibase MediaInfo entities. See Extension:WikibaseMediaInfo/Lua. This is supported by Structured Data on Commons. See Commons:Structured data/Lua.

mw.bcmath
BCmath provides arbitrary-precision arithmetic to Lua modules. See BCmath documentation via "LDoc" link at Extension:BCmath.

mw.smw
Semantic Scribunto provides native support for the Scribunto extension to Semantic MediaWiki extension.

mw.ext.data
JsonConfig provides access to localizable tabular and map data. See Extension:JsonConfig/Tabular. Tabular Data and GeoJSON Map Data is supported in Commons "Data:" namespace.

mw.ext.cargo
Cargo provides a means to query its data store from Lua. See Extension:Cargo/Other features.

mw.ext.cattools
CategoryToolbox provides a means to check from Lua if a certain page belongs to a category

mw.ext.FlaggedRevs
FlaggedRevs provides a means to access the stability settings of a page from Lua.

mw.ext.TitleBlacklist
TitleBlacklist provides a means to test and obtain information about blacklisted page naming entries from Lua.

mw.ext.ParserFunctions
ParserFunctions provides a means to evaluate a parser function expressions from Lua.

mw.ext.articlePlaceholder
ArticlePlaceholder provides a means to override default Wikibase renderings from Lua. See Extension:ArticlePlaceholder/Module:AboutTopic.

Changed functions
The following functions have been modified:
 * setfenv
 * getfenv: May not be available, depending on the configuration. If available, attempts to access parent environments will fail.
 * getmetatable: Works on tables only to prevent unauthorized access to parent environments.
 * tostring: Pointer addresses of tables and functions are not provided. This is to make memory corruption vulnerabilities more difficult to exploit.
 * pairs
 * ipairs: Support for the __pairs and __ipairs metamethods (added in Lua 5.2) has been added.
 * pcall
 * xpcall: Certain internal errors cannot be intercepted.
 * require: Can fetch certain built-in modules distributed with Scribunto, as well as modules present in the Module namespace of the wiki. To fetch wiki modules, use the full page name including the namespace. Cannot otherwise access the local filesystem.

Removed functions and packages
The following packages are mostly removed. Only those functions listed are available:
 * package.*: Filesystem and C library access has been removed. Available functions and tables are:
 * package.loaded
 * package.preload
 * package.loaders: Loaders which access the local filesystem or load C libraries are not present. A loader for Module-namespace pages is added.
 * package.seeall


 * os.*: There are some insecure functions in here, such as os.execute, which can't be allowed. Available functions are:
 * os.clock
 * os.date
 * os.difftime
 * os.time


 * debug.*: Most of the functions are insecure. Available functions are:
 * debug.traceback

The following functions and packages are not available:
 * collectgarbage
 * module
 * coroutine.*: No application is known for us, so it has not been reviewed for security.
 * dofile
 * loadfile
 * io.*, file.*: Allows local filesystem access, which is insecure.
 * load
 * loadstring: These were omitted to allow for static analysis of the Lua source code. Also, allowing these would allow Lua code to be added directly to article and template pages, which was not desired for usability reasons.
 * print: This was discussed on wikitech-l and it was decided that it should be omitted in favour of return values, to improve code quality. If necessary, mw.log may be used to output information to the debug console.
 * string.dump: May expose private data from parent environments.

Additional caveats

 * Referential data structures: Circular data structures and data structures where the same node may be reached by more than one path cannot be correctly sent to PHP. Attempting to do so will cause undefined behavior. This includes (but is not limited to) returning such data structures from the module called by  and passing such data structures as parameters to Scribunto library functions that are implemented as callbacks into PHP. Such data structures may be used freely within Lua, including as the return values of modules loaded with.

Writing Scribunto libraries
This information is useful to developers writing additional Scribunto libraries, whether for inclusion in Scribunto itself or for providing an interface for their own extensions.

A Scribunto library will generally consist of five parts:


 * The PHP portion of the library.
 * The Lua portion of the library.
 * The PHP portion of the test cases.
 * The Lua portion of the test cases.
 * The documentation.

Existing libraries serve as a good example.

Library
The PHP portion of the library is a class that must extend. See the documentation for that class for implementation details. In the Scribunto extension, this file should be placed in, and a mapping added to. Other extensions should use the ScribuntoExternalLibraries hook. In either case, the key should match the Lua module name ("mw.name" for libraries in Scribunto, or "mw.ext.name" for extension libraries).

The Lua portion of the library sets up the table containing the functions that can be called from Lua modules. In the Scribunto extension, the file should be placed in. This file should generally include boilerplate something like this:

The module in  (load this with  ) contains some functions that may be helpful.

Be sure to run the Scribunto test cases with your library loaded, even if your library doesn't itself provide any test cases. The standard test cases include tests for things like libraries adding unexpected global variables. Also, if the library is loaded with PHP, any upvalues that its Lua functions have will not be reset between #invoke's. Care must be taken to ensure that modules can't abuse this to transfer information between #invoke's.

Test cases
The Scribunto extension includes a base class for test cases,, which will run the tests against both the LuaSandbox and LuaStandalone engines. The library's test case should extend this class, and should not override. In the Scribunto extension, the test case should be in  and added to the array in   (in  ); extensions should add the test case in their own   hook function, probably conditional on whether   is set.

Most of the time, all that is needed to make the test case is this:

class ClassNameTest extends Scribunto_LuaEngineTestBase { protected static $moduleName = 'ClassNameTest'; function getTestModules { return parent::getTestModules + array(             'ClassNameTest' => __DIR__ . '/ClassNameTests.lua';          ); } }

This will load the file  as if it were the page "Module:ClassNameTests", expecting it to return an object with the following properties:


 * count: Integer, number of tests
 * provide( n ): Function that returns three values:, the name of test  , and a string that is the expected output for test.
 * run( n ): Function that runs test  and returns one string.

If  is declared as shown, "Module:TestFramework" is available which provides many useful helper methods. If this is used,  would look something like this:

local testframework = require 'Module:TestFramework' return testframework.getTestProvider( {    -- Tests go here } )

Each test is itself a table, with the following properties:


 * name: The name of the test.
 * func: The function to execute.
 * args: Optional table of arguments to pass to the function.
 * expect: Results to expect.
 * type: Optional "type" of the test, default is "Normal".

The type controls the format of  and how   is called. Included types are:


 * Normal:  is a table of return values, or a string if the test should raise an error.   is simply called.
 * Iterator:  is a table of tables of return values.   is called as with an iterated for loop, and each iteration's return values are accumulated.
 * ToString: Like "Normal", except each return value is passed through.

Test cases in another extension
There are (at least) two ways to run PHPUnit tests:


 * 1) Run phpunit against core, allowing the tests/phpunit/suites/ExtensionsTestSuite.php to find the extension's tests using the UnitTestsList hook. If your extension's test class names all contain a unique component (e.g. the extension's name), the   option may be used to run only your extension's tests.
 * 2) Run phpunit against the extension directory, where it will pick up any file ending in "Test.php".

Either of these will work fine if Scribunto is loaded in LocalSettings.php. And it is easy for method #1 to work if Scribunto is not loaded, as the UnitTestsList hook can easily be written to avoid returning the Scribunto test when  is not set.

But Jenkins uses method #2. For Jenkins to properly run the tests, you will need to add Scribunto as a dependency for your extension. See for an example of how this is done.

If for some reason you need the tests to be able to run using method #2 without Scribunto loaded, one workaround is to add this check to the top of your unit test file:

Documentation
Modules included in Scribunto should include documentation in the Scribunto libraries section above. Extension libraries should include documentation in a subpage of their own extension page, and link to that documentation from the Extension libraries subsection above.

License
This manual is derived from the Lua 5.1 reference manual, which is available under the MIT license.

This derivative manual may also be copied under the terms of the same license.