Extension:Scribunto/Lua reference manual
<languages /> Template:Shortcut <translate> This manual documents <tvar name=lua>Template:Ll</tvar> as it is used in MediaWiki with the <tvar name=scribunto>Template:Ll</tvar> extension.</translate> <translate> Some parts are derived from the [<tvar name=url>https://www.lua.org/manual/5.1/index.html</tvar> Lua 5.1 reference manual], which is available under the [[<tvar name=1>#License</tvar>|MIT license]].</translate>
Template:Mbox Template:TOCright
<translate>
Introduction
Getting started
</translate>
<translate> On a MediaWiki wiki with Scribunto enabled, [[<tvar name=help>Special:MyLanguage/Help:Starting a new page</tvar>|create a page]] with a title starting with <tvar name=1>Module:</tvar>, for example "<tvar name=2>Module:Bananas</tvar>".</translate>
<translate> Into this new page, copy the following text:</translate>
local p = {} --<translate nowrap><!--T:2338--> p stands for package</translate>
function p.hello( frame )
return "Hello, world!"
end
return p
<translate> Save that, then on another (non-module) page, as on a sandbox page, write: </translate>
{{#invoke:Bananas|hello}}
<translate>
Except that you should replace "Bananas" with whatever you called your module. This will call the "hello" function exported from that module. The <tvar name=1>{{#invoke:Bananas|hello}}</tvar> will be replaced with the text that the function returned, in this case, "<tvar name=2>Hello, world!</tvar>"
</translate>
<translate> It's generally a good idea to invoke Lua code from the context of a template.</translate> <translate> This means that from the perspective of a calling page, the syntax is independent of whether the template logic is implemented in Lua or in wikitext.</translate> <translate> It also avoids the introduction of additional complex syntax into the content namespace of a wiki.</translate>
<translate>
Module structure
</translate>
<translate> The module itself must return a Lua table containing the functions that may be called by <tvar name=1>{{#invoke:}}</tvar>.</translate>
<translate> Generally, as shown above, a local variable is declared holding a table, functions are added to this table, and the table is returned at the end of the module code.</translate>
<translate> Any functions that are not added to this table, whether local or global, will not be accessible by <tvar name=1>{{#invoke:}}</tvar>, but globals might be accessible from other modules loaded using <tvar name=require_function>require()</tvar>.</translate>
<translate> It is generally good style for the module to declare all functions and variables local.</translate>
<translate>
Accessing parameters from wikitext
Functions called by <tvar name=1>{{#invoke:}}</tvar> will be passed a single parameter, that being a [[<tvar name=anchor1>#frame-object</tvar>|frame object]]. To access the parameters passed to the <tvar name=1>{{#invoke:}}</tvar>, code will typically use the <tvar name=anchor2>args</tvar> table of that frame object. It's also possible to access the parameters passed to the template containing the <tvar name=1>{{#invoke:}}</tvar> by using <tvar name=2>frame:getParent()</tvar> and accessing that frame's <tvar name=3>args</tvar>.
This frame object is also used to access context-specific features of the wikitext parser, such as [[<tvar name=anchor1>#frame:callParserFunction</tvar>|calling parser functions]], [[<tvar name=anchor2>#frame:expandTemplate</tvar>|expanding templates]], and [[<tvar name=anchor3>#frame:preprocess</tvar>|expanding arbitrary wikitext strings]].
Returning text
The module function should usually return a single string; whatever values are returned will be passed through <tvar name=1>tostring()</tvar> and then concatenated with no separator. This string is incorporated into the wikitext as the result of the <tvar name=2>{{#invoke:}}</tvar>.
At this point in the page parse, templates have already been expanded, parser functions and extension tags have already been processed, and [[<tvar name=pst>Special:MyLanguage/Pre-save transforms</tvar>|pre-save transforms]] (i.e., signature tilde expansion, pipe trick, etc.) have already happened. Therefore the module cannot use these features in its output text. For example, if a module returns <tvar name=1>"Hello, [[world]]! {{welcome}}"</tvar>, the page will read "<tvar name=2>Hello, world! {{welcome}}</tvar>".
On the other hand, [[<tvar name=help>Special:MyLanguage/Help:Substitution</tvar>|subst]] is handled at an earlier stage of processing, so with <tvar name=1>{{subst:#invoke:}}</tvar> only other attempted substitutions will be processed. Since the failed substitution will remain in the wikitext, they will then be processed on the next edit. This should generally be avoided.
Module documentation
Scribunto allows modules to be documented by automatically associating the module with a wikitext documentation page; by default, the "/doc" subpage of the module is used for this purpose and is transcluded above the module source code on the module page. For example, the documentation for <tvar name=1>"Module:Bananas"</tvar> would be at <tvar name=2>"Module:Bananas/doc"</tvar>.
This can be configured using the following Template:Ll: </translate>
scribunto-doc-page-name— <translate> Sets the name of the page used for documentation.</translate> <translate> The name of the module (without the Module: prefix) is passed as$1.</translate> <translate> If in the module namespace, the pages specified here will be interpreted as wikitext rather than Lua source and may not be used with{{#invoke:}}.</translate> <translate> The default is "Module:$1/doc", i.e. the /doc subpage of the module.</translate> <translate> Note that parser functions and other brace expansion may not be used in this message.</translate>scribunto-doc-page-does-not-exist— <translate> Message displayed when the doc page does not exist.</translate> <translate> The name of the page is passed as$1.</translate> <translate> The default is empty.</translate>scribunto-doc-page-show— <translate> Message displayed when the doc page does exist.</translate> <translate> The name of the page is passed as$1.</translate> <translate> The default is to transclude the documentation page.</translate>scribunto-doc-page-header— <translate> Header displayed when viewing the documentation page itself.</translate> <translate> The name of the module (with Module: prefix) being documented is passed as$1.</translate> <translate> The default simply displays a short explanation in italics.</translate>
<translate> Note that modules cannot be directly categorized.</translate> <translate> Category insertions can be placed on the documentation page inside <tvar name=1>Template:Tag</tvar> tags, where they will be applied to the module when the documentation page is transcluded onto the module page.</translate>
<translate>
Renaming or moving modules
To rename or move a module, use the Move Page link in the Tools sidebar. You will want to move both the module itself, as well as the subpage containing its documentation.
Redirects
</translate> Template:MW version <translate> Since release 1.42, Scribunto recognizes one particular syntax for redirects (so they’re highlighted on special pages, appear on <tvar name=1>Special:WhatLinksHere</tvar>, and so on), and also produces redirects when renaming/moving a module, similarly to how renaming of wikitext pages works (before that, module renames left no redirects behind, now extra rights are needed to suppress the redirect).
To manually create a module redirect, use the following syntax (which is valid Lua code, and worked like a redirect even before 1.42, but without MediaWiki recognizing it as such): </translate>
return require [[Module:Foo]]
<translate>
Replace <tvar name=1>Foo</tvar> with the name of the module you'd like to redirect to.
Please note that other similarly valid Lua syntax variations (e.g. using quotation marks instead of square brackets, using parentheses around the <tvar name=1>require</tvar> parameter, or even whitespace variations) are still not recognized by MediaWiki as redirects.
Lua language
Tokens
</translate>
Template:Anchor <translate> A name (also called an identifier) in Lua can be any string of letters, digits, and underscores, not beginning with a digit. Names are case-sensitive; "foo", "Foo", and "FOO" are all different names.
The following keywords are reserved and may not be used as names: </translate>
andbreakdoelseelseifendfalseforfunctionifinlocalnilnotorrepeatreturnthentrueuntilwhile
<translate> Names starting with an underscore followed by uppercase letters are reserved for internal Lua global variables.
Other tokens are: </translate>
#%()*+,---....../:;<<====>>=[]^{}~=
<translate>
Comments
A comment starts with a <tvar name=1>--</tvar> anywhere outside a string. If the <tvar name=1>--</tvar> is immediately followed by [[<tvar name=2>#long brackets</tvar>|an opening long bracket]], the comment continues to the corresponding closing long bracket; otherwise the comment runs to the end of the current line.
</translate>
-- <translate nowrap><!--T:1265--> A comment in Lua starts with a double-hyphen and runs to the end of the line.</translate>
<translate nowrap><!--T:2342-->
--[[ Multi-line strings & comments
are adorned with double square brackets. ]]</translate>
<translate nowrap><!--T:2343--> --[=[ Comments like this can have other --[[comments]] nested. ]=]</translate>
<translate nowrap><!--T:2344-->
--[==[ Comments like this can have other
--[===[ long --[=[comments]=] --nested
]===] multiple times, even if all of them are
--[[ not delimited with matching long brackets! ]===]
]==]</translate>
<translate>
Data types
Lua is a dynamically-typed language, which means that variables and function arguments have no type, only the values assigned to them. All values carry a type.
Lua has eight basic data types, however only six are relevant to the Scribunto extension. The <tvar name=type_function>type()</tvar> function will return the type of a value.
The <tvar name=tostring_function>tostring()</tvar> function will convert a value to a string. The <tvar name=tonumber_function>tonumber()</tvar> function will convert a value to a number if possible, and otherwise will return nil. There are no explicit functions to convert a value to other data types.
Numbers are automatically converted to strings when used where a string is expected, e.g. when used with the concatenation operator. Strings recognized by <tvar name=tonumber_function>tonumber()</tvar> are automatically converted to numbers when used with arithmetic operators. When a boolean value is expected, all values other than nil and false are considered to be true.
nil
Template:Luai is the data type of <tvar name=1>Template:Luai</tvar>, which exists to represent the absence of a value.
Nil may not be used as a key in a table, and there is no difference between an unassigned table key and a key assigned a nil value.
When converted to a string, the result is <tvar name=1>Template:Luai</tvar>. When converted to boolean, nil is considered false. </translate>
<translate> Note: Lua does make a distinction between <tvar name=1>Template:Luai</tvar> and nothing at all in some limited situations.</translate> <translate> For example, <tvar name=1>Template:Luai</tvar> returns <tvar name=2>Template:Luai</tvar>, but <tvar name=3>Template:Luai</tvar> throws an error, as the first parameter is required.</translate> <translate> This distinction is particularly relevant to the <tvar name=1>select()</tvar> function.</translate>
<translate>
boolean
Boolean values are <tvar name=1>Template:Luai</tvar> and <tvar name=2>Template:Luai</tvar>.
When converted to a string, the result is <tvar name=1>Template:Luai</tvar> or <tvar name=2>Template:Luai</tvar>.
Unlike many other languages, boolean values may not be directly converted to numbers. And unlike many other languages, only <tvar name=1>Template:Luai</tvar> and nil are considered false for boolean conversion; the number 0 and the empty string are both considered true.
string
Lua strings are considered a series of 8-bit bytes; it is up to the application to interpret them in any particular encoding.
String literals may be delimited by either single or double quotes (<tvar name=1>'</tvar> or <tvar name=2>"</tvar>); like JavaScript and unlike PHP, there is no difference between the two. The following escape sequences are recognized:
</translate>
<translate>
\a(bell, byte 7)\b(backspace, byte 8)\t(horizontal tab, byte 9)\n(newline, byte 10)\v(vertical tab, byte 11)\f(form feed, byte 12)\r(carriage return, byte 13)\"(double quote, byte 34)\'(single quote, byte 39)\\(backslash, byte 92)
</translate>
<translate> A literal newline may also be included in a string by preceding it with a backslash. Bytes may also be specified using an escape sequence <tvar name=1>'\ddd'</tvar>, where <tvar name=2>ddd</tvar> is the decimal value of the byte in the range 0–255. To include Unicode characters using escape sequences, the individual bytes for the UTF-8 encoding must be specified; in general, it will be more straightforward to enter the Unicode characters directly. </translate>
Template:Anchor
<translate> Literal strings can also be defined using long brackets.</translate>
<translate> An opening long bracket consists of an opening square bracket followed by zero or more equal signs followed by another opening square bracket, e.g. <tvar name=1>[[</tvar>, <tvar name=2>[=[</tvar>, or <tvar name=3>[=====[</tvar>.</translate>
<translate> The opening long bracket must be matched by the corresponding closing long bracket, e.g. <tvar name=1>]]</tvar>, <tvar name=2>]=]</tvar>, or <tvar name=3>]=====].</tvar></translate>
<translate> As a special case, if an opening long bracket is immediately followed by a newline then the newline is not included in the string, but a newline just before the closing long bracket is kept.</translate>
<translate> Strings delimited by long brackets do not interpret escape sequences.</translate>
-- <translate nowrap><!--T:1284--> This long string</translate>
foo = [[
bar\tbaz
]]
-- <translate nowrap><!--T:1285--> is equivalent to this quote-delimited string</translate>
foo = 'bar\\tbaz\n'
<translate> Note that all strings are considered true when converted to boolean. This is unlike most other languages, where the empty string is usually considered false.
number
Lua has only one numeric type, which is typically represented internally as a 64-bit double-precision floating-point value. In this format, integers between <tvar name="1">-9007199254740991 (-253 + 1)</tvar> and <tvar name="2">9007199254740991 (253 - 1)</tvar> may be represented exactly; larger numbers and numbers with a fractional part may suffer from round-off error.
</translate>
<translate> Number constants are specified using a period (<tvar name="dot">.</tvar>) as a decimal separator and without grouping separators, e.g. <tvar name="n">123456.78</tvar>.</translate>
<translate> Numbers may also be represented using E notation without spaces, e.g. <tvar name=1>1.23e-10</tvar>, <tvar name=2>123.45e20</tvar>, or <tvar name=3>1.23E+5</tvar>.</translate>
<translate> Integers may also be specified in hexadecimal notation using a <tvar name="0x">0x</tvar> prefix, e.g. <tvar name="0x3A">0x3A</tvar>.</translate>
<translate> A handful of number values are handled in a special way:
- Postive and negative infinity, which evalute to being greater or less than every other number, respectively (except the NaNs - see below). These can be accessed in two ways: through the <tvar name="math">Template:Luai</tvar> library, as Template:Luai and Template:Luai, or through numerical operations such as <tvar name=1>
1/0</tvar> and <tvar name=2>-1/0</tvar>. - Lua occasionally distinguishes <tvar name=3>
0</tvar> and <tvar name=4>-0</tvar> (see the IEEE 754 for more information on signed zeros). <tvar name=5>0</tvar> and <tvar name=6>-0</tvar> are strictly equivalent for almost all purposes, but behave differently in a small number of numerical operations (e.g. <tvar name=7>1/0</tvar> returns infinity, while <tvar name=8>1/-0</tvar> returns negative infinity). The distinction also affects conversions from number to string (and vice-versa). - Positive and negative NaN (standing for Not a Number). No constant is provided for either of these, but <tvar name=9>
0/0</tvar> evaluates to negative NaN. Note that both NaNs have the unique quality that any comparison which involves them evaluates to <tvar name=10>Template:Luai</tvar> (which means they do not even evaluate as being equal to themselves). The only practical distinction between the two is on type conversion to and from string (see below).
Note that all numbers (including <tvar name=1>0, -0</tvar>, the infinities and NaNs) are considered true when converted to boolean. This is unlike most other languages, where <tvar name=2>0</tvar> is usually considered false. When converted to a string, finite numbers are represented in decimal, and E notation if 1014 or greater (e.g. <tvar name="1e+14">Template:Luai</tvar>); the infinities are <tvar name="inf">Template:Luai</tvar> and <tvar name="-inf">Template:Luai</tvar>; and the NaNs are <tvar name="nan">Template:Luai</tvar> and <tvar name="-nan">Template:Luai</tvar>.
</translate>
<translate> Template:Red: the Lua interpreter will treat all instances of <tvar name=1>0</tvar> and <tvar name=2>-0</tvar> as whichever of the two is encountered first when the script is compiled, which means that the return values of <tvar name=3>Template:Luai</tvar>, <tvar name=4>Template:Luai</tvar> (and so on) are affected by where they occur in the code.</translate>
<translate> This can cause unexpected results, particularly if all instances of <tvar name=1>0</tvar> are converted to <tvar name=2>Template:Luai</tvar> on return.</translate>
<translate> If necessary, this can be circumvented by generating zero values using <tvar name=1>Template:Luai</tvar> and <tvar name=2>Template:Luai</tvar>, which doesn't seem to cause or be affected by the issue. See <tvar name=3>[1]</tvar>.</translate>
<translate>
table
Lua tables are associative arrays, much like PHP arrays and JavaScript objects.
Tables are created using curly braces. The empty table is <tvar name=1>{}</tvar>. To populate fields on creation, a comma- and/or semicolon-separated list of field specifiers may be included in the braces. These take any of several forms:
</translate>
- <translate> <tvar name=1>
[expression1] = expression2</tvar> uses the (first) value of <tvar name=2>expression1</tvar> as the key and the (first) value of <tvar name=9>expression2</tvar><tvar name=3></tvar> as the value.</translate> - <translate> <tvar name=4>
name = expression</tvar> is equivalent to <tvar name=5>["name"] = expression</tvar></translate> - <translate> <tvar name=6>
expression</tvar> is roughly equivalent to <tvar name=7>[i] = expression</tvar>, where <tvar name=8>i</tvar> is an integer starting at 1 and incrementing with each field specification of this form. If this is the last field specifier and the expression has multiple values, all values are used; otherwise only the first is kept.</translate>
<translate>
The fields in a table are accessed using bracket notation, e.g. <tvar name=1>table[key]</tvar>. String keys that are also valid [[<tvar name=2>#name</tvar>|names]] may also be accessed using dot notation, e.g. <tvar name=3>table.key</tvar> is equivalent to <tvar name=4>table['key']</tvar>. Calling a function that is a value in the table may use colon notation; for example, <tvar name=5>table:func( ... )</tvar>, which is equivalent to <tvar name=6>table['func']( table, ... )</tvar> or <tvar name=7>table.func( table, ... )</tvar>.
</translate>
Template:Anchor <translate> An array (also called a sequence or list) is a table with non-nil values for all positive integers from 1 to N and no value (nil) for all positive integers greater than N. Many Lua functions operate only on arrays, and ignore non-positive-integer keys.
Unlike many other languages such as PHP or JavaScript, any value except nil and NaN may be used as a key and no type conversion is performed. These are all valid and distinct: </translate>
-- <translate nowrap><!--T:1299--> Create table</translate>
t = {}
t["foo"] = "foo"
t.bar = "bar"
t[1] = <translate nowrap><!--T:2444--> "one"</translate>
t[2] = <translate nowrap><!--T:2445--> "two"</translate>
t[3] = <translate nowrap><!--T:2446--> "three"</translate>
t[12] = <translate nowrap><!--T:2447--> "the number twelve"</translate>
t["12"] = <translate nowrap><!--T:2448--> "the string twelve"</translate>
t[true] = "true"
t[tonumber] = <translate nowrap><!--T:2449--> "yes, even functions may be table keys"</translate>
t[t] = <translate nowrap><!--T:2450--> "yes, a table may be a table key too. Even in itself."</translate>
-- <translate nowrap><!--T:1300--> This creates a table roughly equivalent to the above</translate>
t2 = {
foo = "foo",
bar = "bar",
<translate nowrap><!--T:2499--> "one"</translate>,
<translate nowrap><!--T:2500--> "two"</translate>,
[12] = <translate nowrap><!--T:2451--> "the number twelve",</translate>
["12"] = <translate nowrap><!--T:2452--> "the string twelve",</translate>
<translate nowrap><!--T:2453--> "three",</translate>
[true] = "true",
[tonumber] = <translate nowrap><!--T:2454--> "yes, even functions may be table keys",</translate>
}
t2[t2] = <translate nowrap><!--T:2455--> "yes, a table may be a table key too. Even in itself."</translate>
<translate> Similarly, any value except nil may be stored as a value in a table. Storing nil is equivalent to deleting the key from the table, and accessing any key that has not been set will result in a nil value.
Note that tables are never implicitly copied in Lua; if a table is passed as an argument to the function and the function manipulates the keys or values in the table, those changes will be visible in the caller.
When converted to a string, the usual result is "table" but may be overridden using the <tvar name=1>__tostring</tvar> [[<tvar name=2>#Metatables</tvar>|metamethod]]. Even the empty table is considered true as a boolean.
function
Functions in Lua are first-class values: they may be created anonymously, passed as arguments, assigned to variables, and so on.
Functions are created using the <tvar name=1>function</tvar> keyword, and called using parentheses. Syntactic sugar is available for named functions, local functions, and functions that act like member functions to a table. See [[<tvar name=anchor1>#Function declarations</tvar>|Function declarations]] and [[<tvar name=anchor2>#Function calls</tvar>|Function calls]] below for details.
Lua functions are closures, meaning that they maintain a reference to the scope in which they are declared and can access and manipulate variables in that scope.
Like tables, if a function is assigned to a different variable or passed as an argument to another function, it is still the same underlying "function object" that will be called.
When converted to a string, the result is "function".
Unsupported types
</translate>
Template:Anchor <translate> The userdata type is used to hold opaque values for extensions to Lua written in other languages; for example, a userdata might be used to hold a C pointer or struct. To allow for use of Scribunto in hosting environments where custom-compiled code is not allowed, no such extensions are used. </translate>
Template:Anchor <translate> The thread type represents the handles for coroutines, which are not available in Scribunto's sandbox.
Upvalues
There is a strict limit of max 60 unique upvalues accessed inside a function. An upvalue is a value declared outside of a function and used inside it. As upvalues do count:
- variables (a table with many elements counts as one upvalue)
- functions (only those directly called from function in question, not their dependencies)
A violation of the limit can be triggered by a use of such a variable or function, not by its mere presence or availability. Repeated access to same upvalue does not exhaust the limit further.
Metatables
Every table may have an associated table known as a metatable. The fields in the metatable are used by some operators and functions to specify different or fallback behavior for the table. The metatable for a table may be accessed using the <tvar name=getmetatable>getmetatable()</tvar> function, and set with the <tvar name=setmetatable>setmetatable()</tvar> function.
When being accessed for their meta functions, metatable fields are accessed as if with <tvar name=1>rawget()</tvar>.
Metatable fields that affect the table itself are: </translate>
- __index
- <translate> This is used when a table access
t[key]would return nil.</translate> <translate> If the value of this field is a table, the access will be repeated in that table, i.e.__index[key](which may invoke that table's metatable's <tvar name=2>__index</tvar>).</translate> <translate> If the value of this field is a function, the function will be called as__index( t, key ).</translate> <translate> The <tvar name=rawget>rawget()</tvar> function bypasses this metamethod.</translate> - __newindex
- <translate> This is used when assigning a key to a table
t[key] = valuewhere <tvar name=1>rawget( t, key )</tvar> would return nil.</translate> <translate> If the value of this field is a table, the assignment will be made to that table instead, i.e.__newindex[key] = value(which may invoke that table's metatable's <tvar name=2>__newindex</tvar>).</translate> <translate> If the value of this field is a function, the function will be called as__newindex( t, key, value ).</translate> <translate> The <tvar name=rawget>rawset()</tvar> function bypasses this metamethod.</translate> - __call
- <translate> This is used when function call syntax is used on a table,
t( ··· ).</translate> <translate> The value must be a function, which is called as something like <tvar name=1>__call( t, ··· )</tvar>.</translate> - Template:Anchor__mode
- <translate> This is used to make tables holding weak references.</translate> <translate> The value must be a string.</translate> <translate> By default, any value that is used as a key or as a value in a table will not be garbage collected.</translate> <translate> But if this metafield contains the letter <tvar name=1>'k'</tvar>, keys may be garbage collected if there are no non-weak references, and if it contains <tvar name=2>'v'</tvar> values may be; in either case, both the corresponding key and value are removed from the table.</translate> <translate> Note that behavior is undefined if this field is altered after the table is used as a metatable.</translate>
<translate> Other metatable fields include: </translate>
<translate>
Note: In Lua, all strings also share a single metatable, in which <tvar name=1>__index</tvar> refers to the <tvar name=2>string</tvar> table. This metatable is not accessible in Scribunto, nor is the referenced <tvar name=3>string</tvar> table; the string table available to modules is a copy.
Variables
Variables are places that store values. There are three kinds of variables in Lua: global variables, local variables, and table fields.
A [[<tvar name=1>#name</tvar>|name]] represents a global or local variable (or a function argument, which is just a kind of local variable). Variables are assumed to be global unless explicitly declared as local using the <tvar name=2>local</tvar> keyword. Any variable that has not been assigned a value is considered to have a nil value.
Global variables are stored in a standard Lua table called an environment; this table is often available as the global variable <tvar name=1>_G</tvar>. It is possible to set a metatable for this global variable table; the <tvar name=2>__index</tvar> and <tvar name=3>__newindex</tvar> metamethods will be called for accesses of and assignments to global variables just as they would for accesses of and assignments to fields in any other table.
The environment for a function may be accessed using the <tvar name=1>getfenv()</tvar> function and changed using the <tvar name=2>setfenv()</tvar> function; in Scribunto, these functions are severely restricted if they are available at all.
Local variables are lexically scoped; see [[<tvar name=1>#Local variable declarations</tvar>|Local variable declarations]] for details.
Expressions
An expression is something that has values: literals (numbers, strings, true, false, nil), anonymous function declarations, table constructors, variable references, function calls, the [[<tvar name=1>#varargs</tvar>|vararg expression]], expressions wrapped in parentheses, unary operators applied to expressions, and expressions combined with binary operators.
Most expressions have one value; function calls and the vararg expression can have any number. Note that wrapping a function call or vararg expression in parentheses will lose all except the first value. </translate>
Template:Anchor <translate> Expression lists are comma-separated lists of expressions. All except the last expression are forced to one value (dropping additional values, or using nil if the expression has no values); all values from the last expression are included in the values of the expression list.
Arithmetic operators
Lua supports the usual arithmetic operators: addition, subtraction, multiplication, division, modulo, exponentiation, and negation.
When all operands are numbers or strings for which <tvar name=1>tonumber()</tvar> returns non-nil, the operations have their usual meaning.
If either operand is a table with an appropriate [[<tvar name=1>#Metatables</tvar>|metamethod]], the metamethod will be called. </translate>
| <translate> Operator</translate> | <translate> Function</translate> | <translate> Example</translate> | <translate> Metamethod</translate> | <translate> Notes</translate> |
|---|---|---|---|---|
| + | <translate> Addition</translate> | a + b | __add | |
| - | <translate> Subtraction</translate> | a - b | __sub | |
| * | <translate> Multiplication</translate> | a * b | __mul | |
| / | <translate> Division</translate> | a / b | __div | <translate> division by zero is not an error; NaN or infinity will be returned</translate> |
| % | <translate> Modulo</translate> | a % b | __mod | <translate> defined as <tvar name=1>a % b == a - math.floor( a / b ) * b</tvar></translate>
|
| ^ | <translate> Exponentiation</translate> | a ^ b | __pow | <translate> non-integer exponents are allowed</translate> |
| - | <translate> Negation</translate> | -a | __unm |
<translate>
Relational operators
The relational operators in Lua are <tvar name=1>==</tvar>, <tvar name=2>~=</tvar>, <tvar name=3><</tvar>, <tvar name=4>></tvar>, <tvar name=5><=</tvar>, and <tvar name=6>>=</tvar>. The result of a relational operator is always a boolean.
Equality (<tvar name=1>==</tvar>) first compares the types of its operands; if they are different, the result is false. Then it compares the values: nil, boolean, number, and string are compared in the expected manner. Functions are equal if they refer to the exact same function object; <tvar name=2>function() end == function() end</tvar> will return false, as it is comparing two different anonymous functions. Tables are by default compared in the same manner, but this may be changed using the <tvar name=4>__eq</tvar> [[<tvar name=3>#Metatables</tvar>|metamethod]].
Inequality (<tvar name=1>~=</tvar>) is the exact negation of equality.
For the ordering operators, if both are numbers or both are strings, they are compared directly. Next, metamethods are checked:
- <tvar name=1>
a < b</tvar> uses <tvar name=2>__lt</tvar> - <tvar name=3>
a <= b</tvar> uses <tvar name=4>__le</tvar> if available, or if <tvar name=5>__lt</tvar> is available then it is considered equivalent to <tvar name=6>not ( b < a )</tvar> - <tvar name=7>
a > b</tvar> is considered equivalent to <tvar name=8>b < a</tvar> - <tvar name=9>
a >= b</tvar> is considered equivalent to <tvar name=10>b <= a</tvar>
If the necessary metamethods are not available, an error is raised.
Logical operators
The logical operators are <tvar name=1>and</tvar>, <tvar name=2>or</tvar>, and <tvar name=3>not</tvar>. All use the standard interpretation where nil and false are considered false and anything else is considered true.
For <tvar name=1>and</tvar>, if the left operand is considered false then it is returned and the second operand is not evaluated; otherwise the second operand is returned.
For <tvar name=1>or</tvar>, if the left operand is considered true then it is returned and the second operand is not evaluated; otherwise the second operand is returned.
For <tvar name=1>not</tvar>, the result is always true or false.
Note that <tvar name=1>and</tvar> and <tvar name=2>or</tvar> short circuit. For example, <tvar name=3>foo() or bar()</tvar> will only call <tvar name=4>bar()</tvar> if <tvar name=5>foo()</tvar> returns false or nil as its first value.
Concatenation operator
The concatenation operator is two dots, used as <tvar name=2>a .. b</tvar>. If both operands are numbers or strings, they are converted to strings and concatenated. Otherwise if a <tvar name=3>__concat</tvar> [[<tvar name=1>#Metatables</tvar>|metamethod]] is available, it is used. Otherwise, an error is raised.
Note that Lua strings are immutable and Lua does not provide any sort of "string builder", so a loop that repeatedly does <tvar name=1>a = a .. b</tvar> will have to create a new string for each iteration and eventually garbage-collect the old strings. If many strings need concatenating, it may be faster to use <tvar name=2>string.format()</tvar> or to insert all the strings into a [[<tvar name=anchor2>#sequence</tvar>|sequence]] and use <tvar name=3>table.concat()</tvar> at the end.
Length operator
The length operator is <tvar name=2>#</tvar>, used as <tvar name=3>#a</tvar>. If <tvar name=4>a</tvar> is a string, it returns the length in bytes. If <tvar name=5>a</tvar> is a [[<tvar name=1>#sequence</tvar>|sequence]] table, it returns the length of the sequence.
If <tvar name=1>a</tvar> is a table that is not a sequence, the <tvar name=2>#a</tvar> may return 0 or any value N such that <tvar name=3>a[N]</tvar> is not nil and <tvar name=4>a[N+1]</tvar> is nil, even if there are non-nil values at higher indexes. For example,
</translate>
-- <translate nowrap><!--T:1385--> This is not a sequence, because <tvar name=1>a[3]</tvar> is nil and <tvar name=2>a[4]</tvar> is not.</translate>
a = { 1, 2, nil, 4 }
-- <translate nowrap><!--T:1386--> This may output either 2 or 4.</translate>
-- <translate nowrap><!--T:1387--> And this may change even if the table is not modified.</translate>
mw.log( #a )
<translate>
Operator precedence
Lua's operator precedence or order of operations, from highest to lowest: </translate>
^not#-<translate> (negation)</translate>*/%+-<translate> (subtraction)</translate>..<><=>=~===andor
<translate>
Within a precedence level, most binary operators are left-associative, i.e. <tvar name=1>a / b / c</tvar> is interpreted as <tvar name=2>(a / b) / c</tvar>. Exponentiation and concatenation are right-associative, i.e. <tvar name=3>a ^ b ^ c</tvar> is interpreted as <tvar name=4>a ^ (b ^ c)</tvar>.
Function calls
Lua function calls look like those in most other languages: a name followed by a list of arguments in parentheses: </translate>
<translate> func</translate>( <translate> expression-list</translate> )
<translate> As is usual with expression lists in Lua, the last expression in the list may supply multiple argument values.
If the function is called with fewer values in the expression list than there are arguments in the function definition, the extra arguments will have a nil value. If the expression list contains more values than there are arguments, the excess values are discarded. It is also possible for a function to take a variable number of arguments; see [[<tvar name=1>#Function declarations</tvar>|Function declarations]] for details.
Lua also allows direct calling of a function return value, i.e. <tvar name=1>func()()</tvar>. If an expression more complex than a variable access is needed to determine the function to be called, a parenthesized expression may be used in place of the variable access.
Lua has syntactic sugar for two common cases. The first is when a table is being used as an object, and the function is to be called as a method on the object. The syntax </translate>
<translate> table:name</translate>( <translate> expression-list</translate> )
<translate> is exactly equivalent to </translate>
<translate> table.name</translate>( <translate> table</translate>, <translate> expression-list</translate> )
Template:Anchor <translate> The second common case is Lua's method of implementing named arguments by passing a table containing the name-to-value mappings as the only positional argument to the function. In this case, the parentheses around the argument list may be omitted. This also works if the function is to be passed a single literal string. For example, the calls </translate>
<translate> are equivalent to </translate>
<translate> These may be combined; the following calls are equivalent: </translate>
<translate>
Function declarations
The syntax for function declaration looks like this: </translate>
function nameoptional ( var-listoptional )
<translate> block</translate>
end
<translate> All variables in var-list are local to the function, with values assigned from the expression list in the [[<tvar name=1>#Function calls</tvar>|function call]]. Additional local variables may be declared inside the block. </translate>
<translate> When the function is called, the statements in block are executed after local variables corresponding to var-list are created and assigned values. If a [[<tvar name=1>#return</tvar>|return statement]] is reached, the block is exited and the values of the function call expression are those given by the return statement. If execution reaches the end of the function's block without encountering a return statement, the result of the function call expression has zero values.
Lua functions are lexical closures. A common idiom is to declare "private static" variables as locals in the scope where the function is declared. For example, </translate>
-- <translate nowrap><!--T:1411--> This returns a function that adds a number to its argument</translate>
function makeAdder( n )
return function( x )
-- <translate nowrap><!--T:2456--> The variable <tvar name=1>n</tvar> from the outer scope is available here to be added to <tvar name=2>x</tvar></translate>
return x + n
end
end
local add5 = makeAdder( 5 )
mw.log( add5( 6 ) )
-- <translate nowrap><!--T:1413--> prints 11</translate>
Template:Anchor
<translate>
A function may be declared to accept a variable number of arguments, by specifying <tvar name=1>...</tvar> as the final item in the var-list:
</translate>
function nameoptional ( var-list, ... )
<translate> block</translate>
end
-- or
function nameoptional ( ... )
<translate> block</translate>
end
<translate>
Within the block, the varargs expression <tvar name=1>...</tvar> may be used, with the result being all the extra values in the function call. For example,
</translate>
local join = function ( separator, ... )
-- <translate nowrap><!--T:2458--> get the extra arguments as a new table</translate>
local args = { ... }
-- <translate nowrap><!--T:2459--> get the count of extra arguments, correctly</translate>
local n = select( '#', ... )
return table.concat( args, separator, 1, n )
end
join( ', ', 'foo', 'bar', 'baz' )
-- <translate nowrap><!--T:1420--> returns the string "foo, bar, baz"</translate>
<translate>
The <tvar name=1>select()</tvar> function is designed to work with the varargs expression; in particular, <tvar name=2>select( '#', ... )</tvar> should be used instead of <tvar name=3>#{ ... }</tvar> to count the number of values in the varargs expression, because <tvar name=4>{ ... }</tvar> may not be a [[<tvar name=anchor2>#sequence</tvar>|sequence]].
Lua provides syntactic sugar to combine function declaration and assignment to a variable; see [[<tvar name=1>#Function declaration statements</tvar>|Function declaration statements]] for details.
Note that this will not work: </translate>
local factorial = function ( n )
if n <= 2 then
return n
else
return n * factorial( n - 1 )
end
end
<translate> Since the function declaration is processed before the local variable assignment statement is complete, "factorial" inside the function body refers to the (probably undefined) variable of that name in an outer scope. This problem may be avoided by declaring the local variable first and then assigning it in a subsequent statement, or by using the [[<tvar name=1>#Function declaration statements</tvar>|function declaration statement]] syntax.
Statements
A statement is the basic unit of execution: one assignment, control structure, function call, variable declaration, etc. </translate>
Template:Anchor <translate> A chunk is a sequence of statements, optionally separated by semicolons. A chunk is basically considered the body of an anonymous function, so it can declare local variables, receive arguments, and return values. </translate>
Template:Anchor
<translate>
A block is also a sequence of statements, just like a chunk. A block can be delimited to create a single statement: {{<tvar name=4>tmpl|0=do $1 end</tvar>|block}}. These may be used to limit the scope of local variables, or to add a <tvar name=2>return</tvar> or <tvar name=3>break</tvar> in the middle of another block.
Assignments
</translate>
<translate> variable-list</translate> = <translate> expression-list</translate>
<translate>
The <tvar name=1>variable-list</tvar> is a comma-separated list of variables; the <tvar name=2>expression-list</tvar> is a comma-separated list of one or more expressions. All expressions are evaluated before any assignments are performed, so <tvar name=3>a, b = b, a</tvar> will swap the values of a and b.
Local variable declarations
</translate>
local <translate> variable-list</translate>
local <translate> variable-list</translate> = <translate> expression-list</translate>
<translate> Local variables may be declared anywhere within a [[<tvar name=anchor1>#block</tvar>|block]] or [[<tvar name=anchor2>#block</tvar>|chunk]]. The first form, without an expression list, declares the variables but does not assign a value so all variables have nil as a value. The second form assigns values to the local variables, as described in [[<tvar name=anchor3>#Assignments</tvar>|Assignments]] above.
Note that visibility of the local variable begins with the statement after the local variable declaration. So a declaration like <tvar name=1>local x = x</tvar> declares a local variable <tvar name=2>x</tvar> and assigns it the value of <tvar name=2>x</tvar> from the outer scope. The local variable remains in scope until the end of the innermost block containing the local variable declaration.
Control structures
</translate>
Template:Anchor
while <translate> exp</translate> do <translate> block</translate> end
<translate> The while statement repeats a block as long as an expression evaluates to a true value. </translate>
Template:Anchor
repeat <translate> block</translate> until <translate> exp</translate>
<translate> The repeat statement repeats a block until an expression evaluates to a true value. Local variables declared inside the block may be accessed in the expression. </translate>
Template:Anchor
for <translate> name = exp1, exp2, exp3</translate> do <translate> block</translate> end
for <translate> name = exp1, exp2</translate> do <translate> block</translate> end
<translate>
This first form of the for loop will declare a local variable, and repeat the block for values from exp1 to exp2 adding exp3 on each iteration. Note that exp3 may be omitted entirely, in which case 1 is used, but non-numeric values such as <tvar name=1>nil</tvar> and <tvar name=2>false</tvar> are an error. All expressions are evaluated once before the loop is started.
This form of the for loop is roughly equivalent to </translate>
do
local var, limit, step = tonumber( exp1 ), tonumber( exp2 ), tonumber( exp3 )
if not ( var and limit and step ) then
error()
end
while ( step > 0 and var <= limit ) or ( step <= 0 and var >= limit ) do
local name = var
block
var = var + step
end
end
<translate> except that the variables var, limit, and step are not accessible anywhere else. Note that the variable name is local to the block; to use the value after the loop, it must be copied to a variable declared outside the loop. </translate>
Template:Anchor
for <translate> var-list</translate> in <translate> expression-list</translate> do <translate> block</translate> end
<translate> The second form of the for loop works with iterator functions. As in the first form, the expression-list is evaluated only once before beginning the loop.
This form of the for loop is roughly equivalent to </translate>
do
local func, static, var = expression-list
while true do
local var-list = func( static, var )
var = var1 -- <translate nowrap><!--T:2482--> ''var1'' is the first variable in ''var-list''</translate>
if var == nil then
break
end
block
end
end
<translate> except that again the variables func, static, and var are not accessible anywhere else. Note that the variables in var-list are local to the block; to use them after the loop, they must be copied to variables declared outside the loop.
Often the expression-list is a single function call that returns the three values. If the iterator function can be written so it only depends on the parameters passed into it, that would be the most efficient. If not, [<tvar name=url>https://www.lua.org/pil/7.4.html</tvar> Programming in Lua] suggests that a closure be preferred to returning a table as the static variable and updating its members on each iteration. </translate>
Template:Anchor
if <translate> exp1</translate> then <translate> block1</translate> elseif <translate> exp2</translate> then <translate> block2</translate> else <translate> block3</translate> end
<translate>
Executes block1 if exp1 returns true, otherwise executes block2 if exp2 returns true, and block3 otherwise. The <tvar name=1>else block3</tvar> portion may be omitted, and the <tvar name=2>elseif exp2 then block2</tvar> portion may be repeated or omitted as necessary.
</translate>
Template:Anchor
return <translate> expression-list</translate>
<translate> The return statement is used to return values from a function or a [[<tvar name=1>#chunk</tvar>|chunk]] (which is just a function). The expression-list is a comma-separated list of zero or more expressions.
Lua implements tail calls: if expression-list consists of exactly one expression which is a function call, the current stack frame will be reused for the call to that function. This has implication for functions that deal with the call stack, such as <tvar name=anchor1>getfenv()</tvar> and <tvar name=anchor2>debug.traceback()</tvar>.
The return statement must be the last statement in its [[<tvar name=1>#block</tvar>|block]]. If for some reason a return is needed in the middle of a block, an explicit block <tvar name=2>do return end</tvar> may be used.
</translate>
Template:Anchor
break
<translate> The break statement is used to terminate the execution of a while, repeat, or for loop, skipping to the next statement after the loop.
The break statement must be the last statement in its [[<tvar name=anchor>#block</tvar>|block]]. If for some reason a break is needed in the middle of a block, an explicit block <tvar name=1>do break end</tvar> may be used.
Unlike some other languages, Lua does not have a "<tvar name=1>continue</tvar>" statement for loops (i.e. a statement to move onto the next iteration without breaking the loop altogether).</translate>
<translate> It is straightforward to achieve the same effect by nesting a <tvar name=1>repeat ... until true</tvar> block immediately inside the main loop, which will only ever iterate once for each iteration of the main loop (as its condition is always true).</translate>
<translate> Using <tvar name=1>break</tvar> will only end the inner loop, which has the practical effect of causing the main loop to continue onto the next iteration.</translate>
<translate>
If it is necessary to use <tvar name=1>break</tvar> on the main loop, simply declare a variable which is checked each time the inner loop completes, and set it when necessary.
Function calls as statements
A function call may be used as a statement; in this case, the function is being called only for any side effects it may have (e.g. <tvar name=1>mw.log()</tvar> logs values) and any return values are discarded.
Function declaration statements
Lua provides syntactic sugar to make declaring a function and assigning it to a variable more natural. The following pairs of declarations are equivalent </translate>
-- <translate> Basic declaration</translate> function func( var-list ) <translate> block</translate> end func = function ( var-list ) <translate> block</translate> end
-- <translate> Local function</translate> local function func( var-list ) <translate> block</translate> end local func; func = function ( var-list ) <translate> block</translate> end
-- <translate> Function as a field in a table</translate> function table.func( var-list ) <translate> block</translate> end table.func = function ( var-list ) <translate> block</translate> end
-- <translate> Function as a method in a table</translate> function table:func( var-list ) <translate> block</translate> end table.func = function ( self, var-list ) <translate> block</translate> end
<translate>
Note the colon notation here parallels the colon notation for [[<tvar name=1>#Function calls</tvar>|function calls]], adding an implicit argument named <tvar name=2>self</tvar> at the beginning of the arguments list.
Error handling
Errors may be "thrown" using the [[<tvar name=anchor1>#error</tvar>|error()]] and [[<tvar name=anchor2>#assert</tvar>|assert()]] functions. To "catch" errors, use [[<tvar name=anchor3>#pcall</tvar>|pcall()]] or [[<tvar name=anchor4>#xpcall</tvar>|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 [[<tvar name=anchor>#weak tables</tvar>|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.
Basic functions
</translate>
_G
<translate>
This variable holds a reference to the current global variable table; the global variable <tvar name=1>foo</tvar> may also be accessed as <tvar name=2>_G.foo</tvar>. Note, however, that there is nothing special about <tvar name=3>_G</tvar> itself; it may be reassigned in the same manner as any other variable:
</translate>
foo = 1
mw.log( foo ) -- <translate nowrap><!--T:2472--> logs "1"</translate>
_G.foo = 2
mw.log( foo ) -- <translate nowrap><!--T:2473--> logs "2"</translate>
_G = {} -- <translate nowrap><!--T:2474--> <tvar name=1>_G</tvar> no longer points to the global variable table</translate>
_G.foo = 3
mw.log( foo ) -- <translate nowrap><!--T:2475--> still logs "2"</translate>
<translate> The global variable table may be used just like any other table. For example, </translate>
-- <translate nowrap><!--T:2476--> Call a function whose name is stored in a variable</translate>
_G[var]()
-- <translate nowrap><!--T:2477--> Log the names and stringified values of all global variables</translate>
for k, v in pairs( _G ) do
mw.log( k, v )
end
-- <translate nowrap><!--T:2478--> Log the creation of new global variables</translate>
setmetatable( _G, {
__newindex = function ( t, k, v )
mw.log( "Creation of new global variable '" .. k .. "'" )
rawset( t, k, v )
end
} )
_VERSION
<translate> A string containing the running version of Lua, e.g. "Lua 5.1". </translate>
assert
assert( v, message, ... )
<translate>
If <tvar name=1>v</tvar> is nil or false, issues an error. In this case, <tvar name=2>message</tvar> 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 <tvar name=1>v</tvar> is any other value, assert returns all arguments including <tvar name=1>v</tvar> and <tvar name=2>message</tvar>.
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 <tvar name=1>assert</tvar>:
</translate>
-- <translate nowrap><!--T:2479--> This doesn't check for errors</translate>
local result1, result2, etc = func( ... )
-- <translate nowrap><!--T:2480--> This works the same, but does check for errors</translate>
local result1, result2, etc = assert( func( ... ) )
error
error( message, level )
<translate>
Issues an error, with text <tvar name=1>message</tvar>.
<tvar name=1>error</tvar> normally adds some information about the location of the error. If <tvar name=2>level</tvar> is 1 or omitted, that information is the location of the call to <tvar name=1>error</tvar> 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.
</translate>
getfenv
getfenv( f )
<translate>
Note this function may not be available, depending on <tvar name=1>allowEnvFuncs</tvar> in the engine configuration.
Returns an environment (global variable table), as specified by <tvar name=1>f</tvar>:
- If 1, nil, or omitted, returns the environment of the function calling <tvar name=1>
getfenv</tvar>. Often this will be the same as <tvar name=2>_G</tvar>. - 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 <tvar name=1>getfenv</tvar> will return nil instead.
</translate>
getmetatable
getmetatable( table )
<translate> Returns the [[<tvar name=anchor1>#Metatables</tvar>|metatable]] of a [[<tvar name=anchor2>#table</tvar>|table]]. Any other type will return nil.
If the metatable has a <tvar name=1>__metatable</tvar> field, that value will be returned instead of the actual metatable.
</translate>
ipairs
ipairs( t )
<translate>
Returns three values: an iterator function, the table <tvar name=1>t</tvar>, and 0. This is intended for use in the [[<tvar name=anchor>#iterators</tvar>|iterator form of <tvar name=2>for</tvar>]]:
</translate>
for i, v in ipairs( t ) do
-- process each index-value pair
end
<translate> 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 <tvar name=1>__ipairs</tvar> [[<tvar name=2>#Metatables</tvar>|metamethod]]. If that metamethod exists, the call to ipairs will return the three values returned by <tvar name=3>__ipairs( t )</tvar> instead.
</translate>
next
next( table, key )
<translate>
This allows for iterating over the keys in a table. If <tvar name=1>key</tvar> 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 <tvar name=2>next( t ) == nil</tvar>.
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 [[<tvar name=anchor1>#for</tvar>|numerical for]] or [[<tvar name=anchor2>#ipairs</tvar>|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. </translate>
pairs
pairs( t )
<translate>
Returns three values: an iterator function ([[<tvar name=anchor1>#next</tvar>|next]] or a work-alike), the table <tvar name=1>t</tvar>, and nil. This is intended for use in the [[<tvar name=anchor2>#iterators</tvar>|iterator form of <tvar name=2>for</tvar>]]:
</translate>
for k, v in pairs( t ) do
-- <translate nowrap><!--T:2481--> process each key-value pair</translate>
end
<translate>
This will iterate over the key-value pairs in <tvar name=1>t</tvar> just as [[<tvar name=anchor1>#next</tvar>|next]] would; see the documentation for [[<tvar name=anchor2>#next</tvar>|next]] for restrictions on modifying the table during traversal.
The standard behavior may be overridden by providing a <tvar name=1>__pairs</tvar> [[<tvar name=anchor>#Metatables</tvar>|metamethod]]. If that metamethod exists, the call to pairs will return the three values returned by <tvar name=2>__pairs( t )</tvar> instead.
</translate>
pcall
pcall( f, ... )
<translate>
Calls the function <tvar name=1>f</tvar> with the given arguments in protected mode. This means that if an error is raised during the call to <tvar name=1>f</tvar>, 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, <tvar name=1>pcall</tvar> might be defined something like this:
</translate>
function pcall( f, ... )
try
return true, f( ... )
catch ( message )
return false, message
end
end
rawequal
rawequal( a, b )
<translate>
This is equivalent to <tvar name=1>a == b</tvar> except that it ignores any <tvar name=2>__eq</tvar> [[<tvar name=anchor>#Metatables</tvar>|metamethod]].
</translate>
rawget
rawget( table, k )
<translate>
This is equivalent to <tvar name=1>table[k]</tvar> except that it ignores any <tvar name=2>__index</tvar> [[<tvar name=anchor>#Metatables</tvar>|metamethod]].
</translate>
rawset
rawset( table, k, v )
<translate>
This is equivalent to <tvar name=1>table[k] = v</tvar> except that it ignores any <tvar name=2>__newindex</tvar> [[<tvar name=anchor>#Metatables</tvar>|metamethod]].
</translate>
select
select( index, ... )
<translate> If <tvar name=1>index</tvar> is a number, returns all arguments in <tvar name=2>...</tvar> from that index onwards.</translate>
<translate> If <tvar name=1>index</tvar> is the string <tvar name=3>Template:Luai</tvar>, returns the number of arguments in <tvar name=2>...</tvar>.</translate>
<translate>
Note: unlike tables, lists of arguments (including the [[<tvar name=1>#varargs</tvar>|vararg expression]] <tvar name=2>...</tvar>) treat <tvar name=3>Template:Luai</tvar> as a distinct value (see documentation for <tvar name=4>#</tvar> and [[<tvar name=anchor2>#unpack</tvar>|unpack]] for the problem with <tvar name=5>Template:Luai</tvar> in tables). For example:
- <tvar name=6>Template:Luai</tvar> returns <tvar name=7>Template:Luai</tvar>.
- <tvar name=8>Template:Luai</tvar> returns <tvar name=9>Template:Luai</tvar>.
- <tvar name=10>Template:Luai</tvar> returns <tvar name=11>Template:Luai</tvar>.
- <tvar name=12>Template:Luai</tvar> returns <tvar name=13>Template:Luai</tvar>.
In other words, <tvar name=1>select</tvar> is roughly like the following (except that it also handles any <tvar name=2>Template:Luai</tvar> arguments after the final non-nil argument):
</translate>
function select( index, ... )
local t = { ... }
local maxindex = table.maxn( t )
if index == "#" then
return maxindex
else
return unpack( t, index, maxindex )
end
end
setmetatable
setmetatable( table, metatable )
<translate>
Sets the [[<tvar name=anchor1>#Metatables</tvar>|metatable]] of a [[<tvar name=anchor2>#table</tvar>|table]]. <tvar name=1>metatable</tvar> may be nil, but must be explicitly provided.
If the current metatable has a __metatable field, <tvar name=1>setmetatable</tvar> will throw an error.
</translate>
tonumber
tonumber( value, base )
<translate>
Tries to convert <tvar name=1>value</tvar> to a number. If it is already a number or a string convertible to a number, then <tvar name=2>tonumber</tvar> returns this number; otherwise, it returns nil.
The optional <tvar name=1>base</tvar> (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. </translate>
tostring
tostring( value )
<translate>
Converts <tvar name=1>value</tvar> to a string. See [[<tvar name=anchor>#Data types</tvar>|Data types]] above for details on how each type is converted.
The standard behavior for tables may be overridden by providing a <tvar name=1>__tostring</tvar> [[<tvar name=anchor>#Metatables</tvar>|metamethod]]. If that metamethod exists, the call to tostring will return the single value returned by <tvar name=2>__tostring( value )</tvar> instead.
</translate>
type
type( value )
<translate>
Returns the type of <tvar name=1>value</tvar> as a string: <tvar name=2>"nil"</tvar>, <tvar name=3>"number"</tvar>, <tvar name=4>"string"</tvar>, <tvar name=5>"boolean"</tvar>, <tvar name=6>"table"</tvar>, or <tvar name=7>"function"</tvar>.
</translate>
unpack
unpack( table, i, j )
<translate>
Returns values from the given table, something like <tvar name=1>table[i], table[i+1], ···, table[j]</tvar> would do if written out manually. If nil or not given, <tvar name=2>i</tvar> defaults to 1 and <tvar name=3>j</tvar> defaults to <tvar name=4>#table</tvar>.
If the table does not have a value for a particular key, unpack will return nil for that value. For example, <tvar name=1>Template:Luai</tvar> returns <tvar name=2>Template:Luai</tvar>.
Note that results are not deterministic if <tvar name=2>table</tvar> is not a [[<tvar name=anchor1>#sequence</tvar>|sequence]] and <tvar name=1>j</tvar> is nil or unspecified; see [[<tvar name=anchor2>#Length operator</tvar>|Length operator]] for details.
</translate>
xpcall
xpcall( f, errhandler )
<translate>
This is much like <tvar name=1>pcall</tvar>, except that the error message is passed to the function <tvar name=2>errhandler</tvar> before being returned.
In pseudocode, <tvar name=1>xpcall</tvar> might be defined something like this:
</translate>
function xpcall( f, errhandler )
try
return true, f()
catch ( message )
message = errhandler( message )
return false, message
end
end
<translate>
Debug library
</translate>
debug.traceback
<translate> <tvar name=1>debug.traceback</tvar>( message, level )</translate>
<translate> 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 library
</translate>
math.abs
math.abs( x )
<translate>
Returns the absolute value of <tvar name=1>x</tvar>.
</translate>
math.acos
math.acos( x )
<translate>
Returns the arc cosine of <tvar name=1>x</tvar> (given in radians).
</translate>
math.asin
math.asin( x )
<translate>
Returns the arc sine of <tvar name=1>x</tvar> (given in radians).
</translate>
math.atan
math.atan( x )
<translate>
Returns the arc tangent of <tvar name=1>x</tvar> (given in radians).
</translate>
math.atan2
math.atan2( y, x )
<translate>
Returns the arc tangent of <tvar name=1>y/x</tvar> (given in radians), using the signs of both parameters to find the quadrant of the result.
</translate>
math.ceil
math.ceil( x )
<translate>
Returns the smallest integer larger than or equal to <tvar name=1>x</tvar>.
</translate>
math.cos
math.cos( x )
<translate>
Returns the cosine of <tvar name=1>x</tvar> (given in radians).
</translate>
math.cosh
math.cosh( x )
<translate>
Returns the hyperbolic cosine of <tvar name=1>x</tvar>.
</translate>
math.deg
math.deg( x )
<translate>
Returns the angle <tvar name=1>x</tvar> (given in radians) in degrees.
</translate>
math.exp
math.exp( x )
<translate> Returns the value . </translate>
math.floor
math.floor( x )
<translate>
Returns the largest integer smaller than or equal to <tvar name=1>x</tvar>.
</translate>
math.fmod
math.fmod( x, y )
<translate>
Returns the remainder of the division of <tvar name=1>x</tvar> by <tvar name=2>y</tvar> that rounds the quotient towards zero. For example, <tvar name=3>math.fmod( 10, 3 )</tvar> yields <tvar name=4>1</tvar>.
</translate>
math.frexp
math.frexp( x )
<translate>
Returns two values <tvar name=1>m</tvar> and <tvar name=2>e</tvar> such that:
- If <tvar name=1>
x</tvar> is finite and non-zero: <tvar name=2></tvar>, <tvar name=3>e</tvar> is an integer, and the absolute value of <tvar name=4>m</tvar> is in the range <tvar name=5></tvar> - If <tvar name=6>
x</tvar> is zero: <tvar name=7>m</tvar> and <tvar name=8>e</tvar> are <tvar name=9>0</tvar> - If <tvar name=10>
x</tvar> is NaN or infinite: <tvar name=11>m</tvar> is <tvar name=12>x</tvar> and <tvar name=13>e</tvar> is not specified
</translate>
math.huge
<translate> The value representing positive infinity; larger than or equal to any other numerical value. </translate>
math.ldexp
math.ldexp( m, e )
<translate>
Returns <tvar name=1></tvar> (<tvar name=2>e</tvar> should be an integer).
</translate>
math.log
math.log( x )
<translate>
Returns the natural logarithm of <tvar name=1>x</tvar>.
</translate>
math.log10
math.log10( x )
<translate>
Returns the base-10 logarithm of <tvar name=1>x</tvar>.
</translate>
math.max
math.max( x, ... )
<translate> Returns the maximum value among its arguments.
Behavior with NaNs is not specified. With the current implementation, NaN will be returned if <tvar name=1>x</tvar> is NaN, but any other NaNs will be ignored.
</translate>
math.min
math.min( x, ... )
<translate> Returns the minimum value among its arguments.
Behavior with NaNs is not specified. With the current implementation, NaN will be returned if <tvar name=1>x</tvar> is NaN, but any other NaNs will be ignored.
</translate>
math.modf
math.modf( x )
<translate>
Returns two numbers, the integral part of <tvar name=1>x</tvar> and the fractional part of <tvar name=2>x</tvar>. For example, <tvar name=3>math.modf( 1.25 )</tvar> yields <tvar name=4>1, 0.25</tvar>.
</translate>
math.pi
<translate> The value of . </translate>
math.pow
math.pow( x, y )
<translate>
Equivalent to <tvar name=1>x^y</tvar>.
</translate>
math.rad
math.rad( x )
<translate>
Returns the angle <tvar name=1>x</tvar> (given in degrees) in radians.
</translate>
math.random
math.random( m, n )
<translate> Returns a pseudo-random number.
The arguments <tvar name=1>m</tvar> and <tvar name=2>n</tvar> may be omitted, but if specified must be convertible to integers.
- With no arguments, returns a real number in the range <tvar name=1></tvar>
- With one argument, returns an integer in the range <tvar name=2></tvar>
- With two arguments, returns an integer in the range <tvar name=3></tvar>
Note that incorrect output may be produced if <tvar name=4>m</tvar> or <tvar name=5>n</tvar> are less than <tvar name=1>−2147483648</tvar> or greater than <tvar name=2>2147483647</tvar>, or if <tvar name=6>n - m</tvar> is greater than <tvar name=3>2147483646</tvar>.
</translate>
math.randomseed
math.randomseed( x )
<translate>
Sets <tvar name=1>x</tvar> as the seed for the pseudo-random generator.
Note that using the same seed will cause <tvar name=1>math.random</tvar> to output the same sequence of numbers.
</translate>
math.randomseed( tonumber( mw.getContentLanguage():formatDate( "U" ) ) * 10000 + os.clock() * 10000 )
math.sin
math.sin( x )
<translate>
Returns the sine of <tvar name=1>x</tvar> (given in radians).
</translate>
math.sinh
math.sinh( x )
<translate>
Returns the hyperbolic sine of <tvar name=1>x</tvar>.
</translate>
math.sqrt
math.sqrt( x )
<translate>
Returns the square root of <tvar name=1>x</tvar>. Equivalent to <tvar name=2>x^0.5</tvar>.
</translate>
math.tan
math.tan( x )
<translate>
Returns the tangent of <tvar name=1>x</tvar> (given in radians).
</translate>
math.tanh
math.tanh( x )
<translate>
Returns the hyperbolic tangent of <tvar name=1>x</tvar>.
Operating system library
</translate>
os.clock
os.clock()
<translate> Returns an approximation of the amount in seconds of CPU time used by the program. </translate>
os.date
os.date( format, time )
<translate>
- [[<tvar name=anchor>#mw.language:formatDate</tvar>|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 <tvar name=1>format</tvar>. If the format is omitted or nil, <tvar name=2>"%c"</tvar> is used.
If <tvar name=1>time</tvar> is given, it is the time to be formatted (see <tvar name=2>os.time()</tvar>). Otherwise the current time is used.
If <tvar name=1>format</tvar> starts with <tvar name=2>'!'</tvar>, then the date is formatted in UTC rather than the server's local time. After this optional character, if format is the string <tvar name=3>"*t"</tvar>, 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, to allow for leap seconds)
- 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 <tvar name=1>"*t"</tvar>, then date returns the date as a string, formatted according to the same rules as the <tvar name=2>C</tvar> function <tvar name=3>strftime</tvar>. </translate>
os.difftime
os.difftime( t2, t1 )
<translate>
Returns the number of seconds from <tvar name=1>t1</tvar> to <tvar name=2>t2</tvar>.
</translate>
os.time
os.time( table )
<translate> Returns a number representing the current Unix 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 <tvar name=1>"isdst"</tvar>.
Package library
</translate>
require
require( modulename )
<translate> Loads the specified module.
First, it looks in <tvar name=1>package.loaded[modulename]</tvar> to see if the module is already loaded. If so, returns <tvar name=2>package.loaded[modulename]</tvar>.
Otherwise, it calls each loader in the <tvar name=1>package.loaders</tvar> 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 <tvar name=2>package.loaded[modulename]</tvar> and is returned.
See the documentation for <tvar name=1>package.loaders</tvar> for information on the loaders available.
For example, if you have a module "<tvar name=1>Module:Giving</tvar>" containing the following: </translate>
local p = {}
p.someDataValue = <translate nowrap><!--T:2387--> 'Hello!'</translate>
return p
<translate> You can load this in another module with code such as this: </translate>
local giving = require( "Module:Giving" )
local value = giving.someDataValue -- <translate nowrap><!--T:2390--> value is now 'Hello!'</translate>
package.loaded
<translate> This table holds the loaded modules. The keys are the module names, and the values are the values returned when the module was loaded. </translate>
package.loaders
<translate> 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 [[<tvar name=anchor>#require</tvar>|require]]. Otherwise, it must return nil.
Scribunto provides two searchers:
- Look in <tvar name=1>
package.preload[modulename]</tvar> for the loader function - Look in the [[<tvar name=anchor>#Loadable libraries</tvar>|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. </translate>
package.preload
<translate> This table holds loader functions, used by the first searcher Scribunto includes in <tvar name=1>package.loaders</tvar>. </translate>
package.seeall
package.seeall( table )
<translate>
Sets the <tvar name=1>__index</tvar> [[<tvar name=meta>#Metatables</tvar>|metamethod]] for <tvar name=2>table</tvar> to <tvar name=4>_G</tvar>.
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.
Template:Red The string library assumes one-byte character encodings. It cannot handle Unicode characters. To operate on Unicode strings, use the corresponding methods in the [[<tvar name=anchor>#Ustring library</tvar>|Scribunto Ustring library]]. </translate>
string.byte
string.byte( s, i, j )
<translate>
If the string is considered as an array of bytes, returns the byte values for <tvar name=1>s[i]</tvar>, <tvar name=2>s[i+1]</tvar>, <tvar name=3>···</tvar>, <tvar name=4>s[j]</tvar>.
The default value for <tvar name=5>i</tvar> is 1;
the default value for <tvar name=6>j</tvar> is <tvar name=8>i</tvar>.
Identical to <tvar name=7>mw.ustring.byte()</tvar>.
</translate>
string.char
string.char( ... )
<translate> 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. </translate>
local value = string.char( 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x21 ) --<translate nowrap><!--T:2391--> value is now 'Hello!'</translate>
<translate> See <tvar name=1>mw.ustring.char()</tvar> for a similar function that uses Unicode codepoints rather than byte values. </translate>
string.find
string.find( s, pattern, init, plain )
<translate>
Looks for the first match of <tvar name=1>pattern</tvar> in the string <tvar name=2>s</tvar>. If it finds a match, then <tvar name=3>find</tvar> returns the offsets in <tvar name=4>s</tvar> 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 <tvar name=1>init</tvar> specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument <tvar name=2>plain</tvar> turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in <tvar name=3>pattern</tvar> being considered "magic".
Note that if <tvar name=1>plain</tvar> is given, then <tvar name=2>init</tvar> must be given as well.
See <tvar name=2>mw.ustring.find()</tvar> for a similar function extended as described in [[<tvar name=anchor2>#Ustring patterns</tvar>|Ustring patterns]] and where the <tvar name=1>init</tvar> offset is in characters rather than bytes.
</translate>
string.format
string.format( formatstring, ... )
<translate> 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 [<tvar name=url>http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html</tvar> <tvar name=1>printf</tvar> format specifiers]:
- Recognized flags are <tvar name=1>
'-', '+', ' ', '#',</tvar> and <tvar name=2>'0'</tvar>. - Integer field widths up to 99 are supported. <tvar name=3>
'*'</tvar> is not supported. - Integer precisions up to 99 are supported. <tvar name=3>
'*'</tvar> is not supported. - Length modifiers are not supported.
- Recognized conversion specifiers are <tvar name=4>
'c', 'd', 'i', 'o', 'u', 'x', 'X', 'e', 'E', 'f', 'g', 'G', 's', '%',</tvar> and the non-standard <tvar name=5>'q'</tvar>. - Positional specifiers (e.g. "<tvar name=6>%2$s</tvar>") are not supported.
The conversion specifier <tvar name=1>q</tvar> is like <tvar name=2> s</tvar>, 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 [[<tvar name=anchor>#Data types</tvar>|Data types]]; other types are not automatically converted to strings. Strings containing NUL characters (byte value 0) are not properly handled.
Identical to <tvar name=1>mw.ustring.format()</tvar>. </translate>
string.gmatch
string.gmatch( s, pattern )
<translate>
Returns an iterator function that, each time it is called, returns the next captures from <tvar name=3>pattern</tvar> over string <tvar name=1>s</tvar>. If <tvar name=2>pattern</tvar> specifies no captures, then the whole match is produced in each call.
For this function, a '<tvar name=1>^</tvar>' at the start of a pattern is not magic, as this would prevent the iteration. It is treated as a literal character.
See <tvar name=1>mw.ustring.gmatch()</tvar> for a similar function for which the pattern is extended as described in [[<tvar name=anchor2>#Ustring patterns</tvar>|Ustring patterns]]. </translate>
string.gsub
string.gsub( s, pattern, repl, n )
<translate> Returns two values:
- A copy of <tvar name="1">
s</tvar> in which all (or the first <tvar name="2">n</tvar>, if given) occurrences of the <tvar name="5">pattern</tvar> have been replaced by a replacement string specified by <tvar name="3">repl</tvar>, which can be a string, a table, or a function. - The total number of matches that occurred.
If <tvar name=1>repl</tvar> is a string, then its value is used for replacement. The character <tvar name=2>%</tvar> works as an escape character: any sequence in <tvar name=3>repl</tvar> of the form <tvar name=4>%d</tvar>,
with <tvar name=5>d</tvar> between 1 and 9, stands for the value of the <tvar name=5>d</tvar>-th captured substring. The sequence <tvar name=6>%0</tvar> stands for the whole match, and the sequence <tvar name=7>%%</tvar> stands for a single <tvar name=2>%</tvar>.
If <tvar name=1>repl</tvar> 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 <tvar name=1>repl</tvar> 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 <tvar name=1>mw.ustring.gsub()</tvar> for a similar function in which the pattern is extended as described in [[<tvar name=anchor2>#Ustring patterns</tvar>|Ustring patterns]]. </translate>
string.len
string.len( s )
<translate>
Returns the length of the string, in bytes. Is not confused by ASCII NUL characters. Equivalent to <tvar name=1>#s</tvar>.
See <tvar name=1>mw.ustring.len()</tvar> for a similar function using Unicode codepoints rather than bytes. </translate>
string.lower
string.lower( s )
<translate> Returns a copy of this string with all ASCII uppercase letters changed to lowercase. All other characters are left unchanged.
See <tvar name=anchor>mw.ustring.lower()</tvar> for a similar function in which all characters with uppercase to lowercase definitions in Unicode are converted. </translate>
string.match
string.match( s, pattern, init )
<translate>
Looks for the first match of <tvar name=3>pattern</tvar> in the string. If it finds one, then <tvar name=1>match</tvar> returns the captures from the pattern; otherwise it returns nil. If <tvar name=2>pattern</tvar> specifies no captures, then the whole match is returned.
A third, optional numerical argument <tvar name=1>init</tvar> specifies where to start the search; its default value is 1 and can be negative.
See <tvar name=2>mw.ustring.match()</tvar> for a similar function in which the pattern is extended as described in [[<tvar name=anchor2>#Ustring patterns</tvar>|Ustring patterns]] and the <tvar name=1>init</tvar> offset is in characters rather than bytes.
</translate>
string.rep
string.rep( s, n )
<translate>
Returns a string that is the concatenation of <tvar name=1>n</tvar> copies of the string <tvar name=2>s</tvar>. Identical to <tvar name=3>mw.ustring.rep()</tvar>.
</translate>
string.reverse
string.reverse( s )
<translate>
Returns a string that is the string <tvar name=1>s</tvar> reversed (bytewise).
</translate>
string.sub
string.sub( s, i, j )
<translate>
Returns the substring of <tvar name=s>s</tvar> that starts at <tvar name=i>i</tvar> and continues until <tvar name=j>j</tvar>; <tvar name=i>i</tvar> and <tvar name=j>j</tvar> can be negative. If <tvar name=j>j</tvar> is nil or omitted, it will continue until the end of the string.
In particular, the call <tvar name=1>string.sub(s,1,j)</tvar> returns a prefix of <tvar name=s>s</tvar> with length <tvar name=j>j</tvar>, and <tvar name=2>string.sub(s, -i)</tvar> returns a suffix of <tvar name=s>s</tvar> with length <tvar name=i>i</tvar>.
See <tvar name=1>mw.ustring.sub()</tvar> for a similar function in which the offsets are characters rather than bytes. </translate>
string.ulower
string.ulower( s )
<translate> An alias for <tvar name=anchor>mw.ustring.lower()</tvar>. </translate>
string.upper
string.upper( s )
<translate> Returns a copy of this string with all ASCII lowercase letters changed to uppercase. All other characters are left unchanged.
See <tvar name=1>mw.ustring.upper()</tvar> for a similar function in which all characters with lowercase to uppercase definitions in Unicode are converted. </translate>
string.uupper
string.uupper( s )
<translate> An alias for <tvar name=1>mw.ustring.upper()</tvar>.
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 (<tvar name=1>
%</tvar>), not backslash (<tvar name=2>\</tvar>).</translate>
<translate>
- Dot (<tvar name=1>
.</tvar>) always matches all characters, including newlines.</translate>
<translate>
- No case-insensitive mode.</translate>
<translate>
- No alternation (the <tvar name=1>
|</tvar> operator).</translate>
<translate>
- Quantifiers (<tvar name=1>
*,+,?</tvar>, and <tvar name=2>-</tvar>) may only be applied to individual characters or character classes, not to capture groups.</translate>
<translate>
- The only non-greedy quantifier is <tvar name=1>
-</tvar>, which is equivalent to PCRE's <tvar name=2>*?</tvar> quantifier.</translate>
<translate>
- No generalized finite quantifier (e.g. the <tvar name=1>
{n,m}</tvar> quantifier in PCRE).</translate>
<translate>
- The only zero-width assertions are <tvar name=1>
^</tvar>, <tvar name=2>$</tvar>, and the <tvar name=5>%f[set]</tvar> "frontier" pattern; assertions such as PCRE's <tvar name=3>\b</tvar> or <tvar name=4>(?=···)</tvar> are not present.</translate>
<translate>
- Patterns themselves do not recognize character escapes such as <tvar name=1>
\ddd</tvar>. However, since patterns are [[<tvar name=anchor>#string</tvar>|strings]] these sort of escapes may be used in the string literals used to create the pattern-string.
</translate>
<translate>
Also note that a pattern cannot contain embedded zero bytes (ASCII NUL, <tvar name=1>"\0"</tvar>). Use <tvar name=2>%z</tvar> instead.
Also see [[<tvar name=anchor>#Ustring patterns</tvar>|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: </translate>
Template:Var
|
<translate> (where <tvar name=x>Template:Var</tvar> is not one of the magic characters <tvar name=3>^$()%.[]*+-?</tvar>) represents the character <tvar name=x>Template:Var</tvar> itself.</translate>
|
|---|---|
.
|
<translate> (a dot) Represents all characters.</translate> |
%a
|
<translate> Represents all ASCII letters.</translate> |
%c
|
<translate> Represents all ASCII control characters.</translate> |
%d
|
<translate> Represents all digits.</translate> |
%l
|
<translate> Represents all ASCII lowercase letters.</translate> |
%p
|
<translate> Represents all punctuation characters.</translate> |
%s
|
<translate> Represents all ASCII space characters.</translate> |
%u
|
<translate> Represents all ASCII uppercase letters.</translate> |
%w
|
<translate> Represents all ASCII alphanumeric characters. Note it doesn't include the underscore character (<tvar name=u>_</tvar>), contrarily to the usual class <tvar name=w>\w</tvar> in regular expressions.</translate>
|
%x
|
<translate> Represents all hexadecimal digits.</translate> |
%z
|
<translate> Represents ASCII NUL, the zero byte.</translate> |
%A
|
<translate> All characters not in <tvar name=a>%a</tvar>.</translate>
|
%C
|
<translate> All characters not in <tvar name=c>%c</tvar>.</translate>
|
%D
|
<translate> All characters not in <tvar name=d>%d</tvar>.</translate>
|
%L
|
<translate> All characters not in <tvar name=l>%l</tvar>.</translate>
|
%P
|
<translate> All characters not in <tvar name=p>%p</tvar>.</translate>
|
%S
|
<translate> All characters not in <tvar name=s>%s</tvar>.</translate>
|
%U
|
<translate> All characters not in <tvar name=u>%u</tvar>.</translate>
|
%W
|
<translate> All characters not in <tvar name=w>%w</tvar>.</translate>
|
%X
|
<translate> All characters not in <tvar name=x>%x</tvar>.</translate>
|
%Z
|
<translate> All characters not in <tvar name=z>%z</tvar>.</translate>
|
%Template:Var
|
<translate> (where <tvar name=y>Template:Var</tvar> is any non-alphanumeric character) represents the character <tvar name=y>Template:Var</tvar>. This is the standard way to escape the magic characters. Any punctuation character (even the non magic) can be preceded by a <tvar name=percent>'%'</tvar> when used to represent itself in a pattern.</translate>
|
[[[:Template:Var]]]
|
<translate> Represents the class which is the union of all characters in <tvar name=set>Template:Var</tvar>. A range of characters can be specified by separating the end characters of the range with a <tvar name=hyphen>' <translate>
The interaction between ranges and classes is not defined. Therefore, patterns like <tvar name=1> |
[^Template:Var]
|
<translate> Represents the complement of <tvar name=set>Template:Var</tvar>, where <tvar name=set>Template:Var</tvar> is interpreted as above.</translate> |
<translate>
Pattern items
A pattern item can be
- a single character class, which matches any single character in the class;</translate>
<translate>
- a single character class followed by <tvar name=1>'
*'</tvar>, which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;</translate>
<translate>
- a single character class followed by <tvar name=1>'
+'</tvar>, which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;</translate>
<translate>
- a single character class followed by <tvar name=1>'
-'</tvar>, which also matches 0 or more repetitions of characters in the class. Unlike <tvar name=2>'*'</tvar>, these repetition items will always match the shortest possible sequence;</translate>
<translate>
- a single character class followed by <tvar name=1>'
?'</tvar>, which matches 0 or 1 occurrence of a character in the class;</translate>
<translate>
- <tvar name=1>
%n</tvar>, for <tvar name=2>n</tvar> between 1 and 9; such item matches a substring equal to the <tvar name=2>n</tvar>-th captured string (see below);</translate>
<translate>
- <tvar name=1>
%bxy</tvar>, where <tvar name=2>x</tvar> and <tvar name=3>y</tvar> are two distinct characters; such item matches strings that start with <tvar name=2>x</tvar>, end with <tvar name=3>y</tvar>, and where the <tvar name=2>x</tvar> and <tvar name=3>y</tvar> are balanced. This means that, if one reads the string from left to right, counting +1 for an <tvar name=2>x</tvar> and -1 for a <tvar name=3>y</tvar>, the ending <tvar name=3>y</tvar> is the first <tvar name=3>y</tvar> where the count reaches 0. For instance, the item <tvar name=4>%b()</tvar> matches expressions with balanced parentheses.
</translate> <translate>
- <tvar name=1>
%f[set]</tvar>, a frontier pattern; such item matches an empty string at any position such that the next character belongs to <tvar name=2>set</tvar> and the previous character does not belong to <tvar name=2>set</tvar>. The set <tvar name=2>set</tvar> is interpreted as previously described. The beginning and the end of the subject are handled as if they were the character <tvar name=3>'\0'</tvar>.</translate>
<translate> 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.</translate>
<translate>
Pattern
A pattern is a sequence of pattern items.
A <tvar name=1>^</tvar> at the beginning of a pattern anchors the match at the beginning of the subject string.</translate> <translate> A <tvar name=1>$</tvar> at the end of a pattern anchors the match at the end of the subject string. At other positions, <tvar name=2>^</tvar> and <tvar name=3>$</tvar> have no special meaning and represent themselves.</translate>
<translate>
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 <tvar name=1>(a*(.)%w(%s*))</tvar>, the part of the string matching <tvar name=2>a*(.)%w(%s*)</tvar> is stored as the first capture (and therefore has number 1); the character matching <tvar name=3>.</tvar> is captured with number 2, and the part matching <tvar name=4>%s*</tvar> 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, <tvar name=1>([a-z])%1</tvar> will match any pair of identical lowercase letters, while <tvar name=2>([a-z])([a-z])([a-z])[a-z]%3%2%1</tvar> will match any 7-letter palindrome.
As a special case, the empty capture <tvar name=1>()</tvar> captures the current string position (a number). For instance, if we apply the pattern <tvar name=2>"()aa()"</tvar> on the string <tvar name=3>"flaaap"</tvar>, there will be two captures: 3 and 5.
Template:Red: Unlike [[<tvar name=anchor1>#Ustring patterns</tvar>|Ustring library patterns]], String library patterns may not contain more than 32 captures. If the pattern has more, then the String function will throw an error. Because the Ustring library has its own maximum of 10,000 bytes for patterns (unlike the String library), it is therefore impossible to use a pattern which exceeds both limits, as it will be incompatible with both libraries.
Table library
Most functions in the table library assume that the table represents a [[<tvar name=anchor>#sequence</tvar>|sequence]].
The functions <tvar name=1>table.foreach()</tvar>, <tvar name=2>table.foreachi()</tvar>, and <tvar name=3>table.getn()</tvar> may be available but are deprecated; use a for loop with <tvar name=4>pairs()</tvar>, a for loop with <tvar name=5>ipairs()</tvar>, or the [[<tvar name=6>#Length operator</tvar>|length operator]] <tvar name=7>#</tvar>, respectively. The function <tvar name=8>table.setn()</tvar> is completely obsolete, however, and will throw an error if used.
</translate>
table.concat
table.concat( table, sep, i, j )
<translate>
Given an array where all elements are strings or numbers, returns <tvar name=1>table[i] .. sep .. table[i+1] ··· sep .. table[j]</tvar>.
The default value for <tvar name=1>sep</tvar> is an empty string, the default for <tvar name=2>i</tvar> is 1, and the default for <tvar name=3>j</tvar> is the length of the table. If <tvar name=2>i</tvar> is greater than <tvar name=3>j</tvar>, it returns an empty string.
</translate>
table.insert
table.insert( table, value )
table.insert( table, pos, value )
<translate>
Inserts element <tvar name=1>value</tvar> at position <tvar name=2>pos</tvar> in <tvar name=3>table</tvar>, shifting up other elements to open space, if necessary. The default value for <tvar name=2>pos</tvar> is the length of the table plus 1, so that a call <tvar name=4>table.insert(t, x)</tvar> inserts <tvar name=5>x</tvar> at the end of table <tvar name=6>t</tvar>.
Elements up to <tvar name=1>#table</tvar> are shifted; see [[<tvar name=anchor1>#Length operator</tvar>|Length operator]] for caveats if the table is not a [[<tvar name=anchor2>#sequence</tvar>|sequence]].
</translate>
<translate> Template:Red: when using the <tvar name=1>pos</tvar> parameter, <tvar name=2>value</tvar> should not be <tvar name=3>nil</tvar>. Attempting to insert an explicit <tvar name=3>nil</tvar> value into the middle of a table will result in undefined behaviour, which may delete elements in the table unpredictably.</translate>
table.maxn
table.maxn( table )
<translate> 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 </translate>
function table.maxn( table )
local maxn, k = 0, nil
repeat
k = next( table, k )
if type( k ) == 'number' and k > maxn then
maxn = k
end
until not k
return maxn
end
table.remove
table.remove( table, pos )
<translate>
Removes from <tvar name=1>table</tvar> the element at position <tvar name=2>pos</tvar>, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for <tvar name=2>pos</tvar> is the length of the table, so that a call <tvar name=3>table.remove( t )</tvar> removes the last element of table <tvar name=4>t</tvar>.
Elements up to <tvar name=1>#table</tvar> are shifted; see [[<tvar name=anchor1>#Length operator</tvar>|Length operator]] for caveats if the table is not a [[<tvar name=anchor2>#sequence</tvar>|sequence]].
</translate>
table.sort
table.sort( table, comp )
<translate>
Sorts table elements in a given order, in-place, from <tvar name=1>table[1]</tvar> to <tvar name=2>table[#table]</tvar>.</translate>
<translate> If <tvar name=1>comp</tvar> is given, then it must be a function that receives two table elements, and returns <tvar name=3>Template:Luai</tvar> when the first is less than the second (so that <tvar name=2>not comp(a[i+1],a[i])</tvar> will be true after the sort).</translate>
<translate> If <tvar name=1>comp</tvar> is not given, then the standard Lua operator <tvar name=2><</tvar> is used instead.</translate>
<translate>
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 <tvar name=1>mw</tvar>.
Base functions
</translate>
mw.addWarning
mw.addWarning( text )
<translate>
Adds a warning which is displayed above the preview when previewing an edit. <tvar name=1>text</tvar> is parsed as wikitext.
</translate>
mw.allToString
mw.allToString( ... )
<translate> Calls <tvar name=1>tostring()</tvar> on all arguments, then concatenates them with tabs as separators. </translate>
mw.clone
mw.clone( value )
<translate> Creates a deep copy of a value. All tables (and their metatables) are reconstructed from scratch. Functions are still shared, however. </translate>
mw.getCurrentFrame
mw.getCurrentFrame()
<translate>
Returns the current [[<tvar name=anchor>#frame-object</tvar>|frame object]], typically the frame object from the most recent <tvar name=1>#invoke</tvar>.
</translate>
mw.incrementExpensiveFunctionCount
mw.incrementExpensiveFunctionCount()
<translate> Adds one to the "expensive parser function" count, and throws an exception if it exceeds the limit (see <tvar name=ExpensiveParserFunctionLimit>Template:Wg</tvar>). </translate>
mw.isSubsting
mw.isSubsting()
<translate>
Returns true if the current <tvar name=1>#invoke</tvar> is being [[<tvar name=help>Special:MyLanguage/Manual:Substitution</tvar>|substed]], <tvar name=2>Template:Luai</tvar> otherwise. See [[<tvar name=anchor>#Returning text</tvar>|Returning text]] above for discussion on differences when substing versus not substing.
</translate>
mw.loadData
mw.loadData( module )
<translate>
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 <tvar name=1>{{#invoke:}}</tvar> can use a significant amount of time. To avoid this issue, <tvar name=2>mw.loadData()</tvar> is provided.
<tvar name=2>mw.loadData</tvar> works like <tvar name=1>require()</tvar>, with the following differences:
- The loaded module is evaluated only once per page, rather than once per <tvar name=1>
{{#invoke:}}</tvar> call.</translate>
<translate>
- The loaded module is not recorded in <tvar name=1>
package.loaded</tvar>.</translate>
<translate>
- The value returned from the loaded module must be a table. Other data types are not supported.</translate>
<translate>
- The returned table (and all subtables) may contain only booleans, numbers, strings, and other tables. Other data types, particularly functions, are not allowed.</translate>
<translate>
- The returned table (and all subtables) may not have a [[<tvar name=anchor2>#Metatables</tvar>|metatable]].</translate>
<translate>
- All table keys must be booleans, numbers, or strings.</translate>
<translate>
- The table actually returned by <tvar name=1>
mw.loadData()</tvar> has metamethods that provide read-only access to the table returned by the module. Since it does not contain the data directly, <tvar name=pairs_function>pairs()</tvar> and <tvar name=ipairs_function>ipairs()</tvar> will work but other methods, including <tvar name=2>#value,next()</tvar>, and the functions in the [[<tvar name=anchor7>#Table library</tvar>|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 <tvar name=1>local data = mw.loadData( 'Module:Convert/data' )</tvar> to efficiently load the data.
</translate>
mw.loadJsonData
mw.loadJsonData( page )
<translate> This is the same as <tvar name=1>mw.loadData()</tvar> above, except it loads data from JSON pages rather than Lua tables.</translate>
<translate> The JSON content must be an array or object.</translate>
<translate> See also <tvar name=1>mw.text.jsonDecode()</tvar>.</translate>
mw.dumpObject
mw.dumpObject( object )
<translate>
Serializes <tvar name=1>object</tvar> to a human-readable representation, then returns the resulting string.
</translate>
mw.log
Template:Anchor
mw.log( ... )
<translate> Passes the arguments to <tvar name=1>mw.allToString()</tvar>, then appends the resulting string to the log buffer.
In the debug console, the function <tvar name=1>print()</tvar> is an alias for this function.
</translate>
mw.logObject
mw.logObject( object )
mw.logObject( object, prefix )
<translate>
Calls <tvar name=2>mw.dumpObject()</tvar> and appends the resulting string to the log buffer. If <tvar name=1>prefix</tvar> 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 <tvar name=3>"prefix = object-string"</tvar>).</translate>
Template:Anchor
<translate>
Frame object
The frame object is the interface to the parameters passed to <tvar name=1>{{#invoke:}}</tvar>, and to the parser.
Note that there is no frame library, and there is no global variable named <tvar name=2>Template:Luai</tvar>. A frame object is typically obtained by being passed as a parameter to the function called by <tvar name=1>{{#invoke:}}</tvar>, and can also be obtained from <tvar name=3>mw.getCurrentFrame()</tvar>.
</translate>
frame.args
<translate> A table for accessing the arguments passed to the frame. For example, if a module is called from wikitext with </translate>
{{#invoke:module|function|arg1|arg2|name=arg3}}
<translate> then <tvar name=1>Template:Luai</tvar> will return <tvar name=2>"arg1"</tvar>, <tvar name=3>Template:Luai</tvar> will return <tvar name=4>"arg2"</tvar>, and <tvar name=5>Template:Luai</tvar> (or <tvar name=6>Template:Luai</tvar>) will return <tvar name=7>"arg3"</tvar>. It is also possible to iterate over arguments using <tvar name=8>Template:Luai</tvar> or <tvar name=9>Template:Luai</tvar>.</translate>
<translate> 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.</translate>
<translate>
Note that values in this table are always strings; <tvar name=tonumber_function>tonumber()</tvar> may be used to convert them to numbers, if necessary. Keys, however, are numbers even if explicitly supplied in the invocation: <tvar name=1>{{#invoke:module|function|1|2=2}}</tvar> gives string values <tvar name=2>"1"</tvar> and <tvar name=3>"2"</tvar> indexed by numeric keys <tvar name=4>1</tvar> and <tvar name=5>2</tvar>.
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, <tvar name=1>frame.args</tvar> 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 <tvar name=2>#frame.args, next( frame.args )</tvar>, and the functions in the [[<tvar name=anchor3>#Table library</tvar>|Table library]].
If preprocessor syntax such as template invocations and triple-brace arguments are included within an argument to <tvar name="invoke1">#invoke</tvar>, 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 <tvar name="pre">Template:Tag</tvar>, <tvar name="nowiki">Template:Tag</tvar>, <tvar name="gallery">Template:Tag</tvar> and <tvar name="ref">Template:Tag</tvar>, are included as arguments to <tvar name="invoke2">#invoke</tvar>, then these tags will be converted to "<tvar name=1>strip marker</tvar>s" — special strings which begin with a delete character (<tvar name=2>ASCII 127</tvar>), to be replaced with HTML after they are returned from #invoke.
</translate>
frame:callParserFunction
<translate>
- Note the use of [[<tvar name=1>#named arguments</tvar>|named arguments]].
Call a [[<tvar name=help>Special:MyLanguage/Help:Magic words#Parser functions</tvar>|parser function]], returning an appropriate string. This is preferable to <tvar name=1>frame:preprocess</tvar>, but 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: </translate>
-- {{ns:0}}
frame:callParserFunction( 'ns', { 0 } )
frame:callParserFunction( 'ns', 0 )
frame:callParserFunction{ name = 'ns', args = { 0 } }
-- {{#tag:nowiki|some text}}
frame:callParserFunction( '#tag', { 'nowiki', 'some text' } )
frame:callParserFunction( '#tag', 'nowiki', 'some text' )
frame:callParserFunction( '#tag:nowiki', 'some text' )
frame:callParserFunction{ name = '#tag', args = { 'nowiki', 'some text' } }
-- {{#tag:ref|some text|name=foo|group=bar}}
frame:callParserFunction( '#tag', { 'ref',
'some text', name = 'foo', group = 'bar'
} )
<translate> Note that, as with <tvar name=1>frame:expandTemplate()</tvar>, the function name and arguments are not preprocessed before being passed to the parser function. </translate>
frame:expandTemplate
frame:expandTemplate{ title = title, args = table }
<translate>
- Note the use of [[<tvar name=1>#named arguments</tvar>|named arguments]].
This is equivalent to a call to <tvar name=5>frame:callParserFunction()</tvar> with function name <tvar name=1>Template:Luai</tvar> (see [[<tvar name=2>Special:MyLanguage/Help:Magic words#Transclusion modifiers</tvar>|Help:Magic words#Transclusion modifiers]]) and with <tvar name=3>Template:Luai</tvar> prepended to <tvar name=4>Template:Luai</tvar>.
This is transclusion. The call: </translate>
frame:expandTemplate{ title = 'template', args = { 'arg1', 'arg2', name = 'arg3' } }
<translate>
does roughly the same thing from Lua that <tvar name=1>{{template|arg1|arg2|name=arg3}}</tvar> 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: </translate>
-- <translate nowrap><!--T:1799--> This is roughly equivalent to wikitext like <tvar name=1>{{template|{{!}}}}</tvar></translate>
frame:expandTemplate{ title = 'template', args = { '|' } }
frame:callParserFunction{ 'msg', { 'template', '|' } }
-- <translate nowrap><!--T:1800--> This is roughly equivalent to wikitext like <tvar name=1>{{template|{{((}}!{{))}}}}</tvar></translate>
frame:expandTemplate{ title = 'template', args = { '{{!}}' } }
frame:callParserFunction{ 'msg', { 'template', '{{!}}' } }
frame:extensionTag
<translate> This is equivalent to a call to <tvar name=6>frame:callParserFunction()</tvar> with function name <tvar name=1>Template:Luai</tvar> (see [[<tvar name=2>Special:MyLanguage/Help:Magic_words#Miscellaneous</tvar>|Help:Magic_words#Miscellaneous]]) and with <tvar name=3>Template:Luai</tvar> and <tvar name=4>Template:Luai</tvar> prepended to <tvar name=5>Template:Luai</tvar>. </translate>
-- <translate nowrap><!--T:1804--> These are equivalent</translate>
frame:extensionTag( 'ref', 'some text', { name = 'foo', group = 'bar' } )
frame:extensionTag{ name = 'ref', content = 'some text', args = { name = 'foo', group = 'bar' } }
frame:callParserFunction( '#tag', { 'ref' ,
'some text', name = 'foo', group = 'bar'
} )
-- <translate nowrap><!--T:1805--> These are equivalent</translate>
frame:extensionTag{ name = 'ref', content = 'some text', args = { 'some other text' } }
frame:callParserFunction( '#tag', { 'ref',
'some text', 'some other text'
} )
frame:getParent
<translate>
Called on the frame created by <tvar name=1>{{#invoke:}}</tvar>, returns the frame for the page that called <tvar name=1>{{#invoke:}}</tvar>. Called on that frame, returns nil.
For instance, if the template <tvar name=1>{{Example}}</tvar> contains the code <tvar name=2>{{#invoke:ModuleName|FunctionName|A|B}}</tvar>, and a page transcludes that template with the code <tvar name=3>{{Example|C|D}}</tvar>, then in <tvar name=4>Module:ModuleName</tvar>, calling <tvar name=5>frame.args[1]</tvar> and <tvar name=6>frame.args[2]</tvar> returns <tvar name=7>"A"</tvar> and <tvar name=8>"B"</tvar>, and calling <tvar name=9>frame:getParent().args[1]</tvar> and <tvar name=10>frame:getParent().args[2]</tvar> returns <tvar name=11>"C"</tvar> and <tvar name=12>"D"</tvar>, with <tvar name=13>frame</tvar> being the first argument in the function call.
</translate>
frame:getTitle
<translate>
Returns the title associated with the frame as a string. For the frame created by <tvar name=1>{{#invoke:}}</tvar>, this is the title of the module invoked.
</translate>
frame:newChild
frame:newChild{ title = title, args = table }
<translate>
- Note the use of [[<tvar name=1>#named arguments</tvar>|named arguments]].
Create a new [[<tvar name=anchor>#frame-object</tvar>|Frame object]] that is a child of the current frame, with optional arguments and title.
This is mainly intended for use in modules that call other modules whose name is defined by the caller (e.g. <tvar name=1>{{#invoke:params|concat_and_invoke}}</tvar>), or in the debug console for testing functions that would normally be called by <tvar name=2>{{#invoke:}}</tvar>. The number of frames that may be created at any one time is limited.
</translate>
frame:preprocess
<translate>
This expands wikitext in the context of the frame, i.e. templates, parser functions, and parameters such as <tvar name="param1">{{{1}}}</tvar> are expanded, and returns the expanded text. Certain special tags written in XML-style notation, such as <tvar name="pre">Template:Tag</tvar>, <tvar name="nowiki">Template:Tag</tvar>, <tvar name="gallery">Template:Tag</tvar> and <tvar name="ref">Template:Tag</tvar>, will be replaced with "[[<tvar name=link>Special:MyLanguage/strip marker</tvar>|strip markers]]" — special strings which begin with a delete character (<tvar name=1>ASCII 127</tvar>), to be replaced with HTML after they are returned from <tvar name=2>#invoke</tvar>.
If you are expanding a single template, use <tvar name=1>frame:expandTemplate</tvar> 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 <tvar name=1>frame:callParserFunction</tvar> for the same reasons.
</translate>
frame:getArgument
<translate> Gets an object for the specified argument, or nil if the argument is not provided.
The returned object has one method, <tvar name=1>object:expand()</tvar>, that returns the expanded wikitext for the argument.
</translate>
frame:newParserValue
<translate>
Returns an object with one method, <tvar name=1>object:expand()</tvar>, that returns the result of <tvar name=2>frame:preprocess( text )</tvar>.
</translate>
frame:newTemplateParserValue
frame:newTemplateParserValue{ title = title, args = table }
<translate>
- Note the use of [[<tvar name=1>#named arguments</tvar>|named arguments]].
Returns an object with one method, <tvar name=1>object:expand()</tvar>, that returns the result of <tvar name=2>frame:expandTemplate</tvar> called with the given arguments.
</translate>
frame:argumentPairs
<translate> Same as <tvar name=1>Template:Luai</tvar>. Included for backwards compatibility.
Hash library
</translate>
mw.hash.hashValue
<translate> <tvar name=1>mw.hash.hashValue</tvar>( algo, value )</translate>
<translate> Hashes a string value with the specified algorithm. Valid algorithms may be fetched using <tvar name=1>mw.hash.listAlgorithms()</tvar>. </translate>
mw.hash.listAlgorithms
mw.hash.listAlgorithms()
<translate> Returns a list of supported hashing algorithms, for use in <tvar name=1>mw.hash.hashValue()</tvar>.
HTML library
<tvar name=1>mw.html</tvar> is a fluent interface for building complex HTML from Lua. On many Wikimedia wikis this was formerly implemented in <tvar name=3>Module:HtmlBuilder</tvar>. A mw.html object can be created using <tvar name=2>mw.html.create</tvar>.
</translate>
Template:Anchor
<translate>
Functions documented as <tvar name=1>mw.html.name</tvar> are available on the global <tvar name=2>mw.html</tvar> table; functions documented as <tvar name=3>mw.html:name</tvar> and <tvar name=4>html:name</tvar> are methods of an <tvar name=6>mw.html</tvar> object (see <tvar name=5>mw.html.create</tvar>).
A basic example could look like this: </translate>
local div = mw.html.create( 'div' )
div
:attr( 'id', 'testdiv' )
:css( 'width', '100%' )
:wikitext( 'Some text' )
:tag( 'hr' )
return tostring( div )
-- Output: <div id="testdiv" style="width:100%;">Some text<hr /></div>
mw.html.create
mw.html.create( tagName, args )
<translate>
Creates a new <tvar name=3>mw.html</tvar> object containing a <tvar name=1>tagName</tvar> html element. You can also pass an empty string or nil as <tvar name=2>tagName</tvar> in order to create an empty <tvar name=3>mw.html</tvar> object.
<tvar name=1>args</tvar> can be a table with the following keys:
- <tvar name=1>
args.selfClosing</tvar>: Force the current tag to be self-closing, even if <tvar name=3>mw.html</tvar> doesn't recognize it as self-closing - <tvar name=2>
args.parent</tvar>: Parent of the current <tvar name=3>mw.html</tvar> instance (intended for internal usage)
</translate>
mw.html:node
html:node( builder )
<translate>
Appends a child <tvar name=3>mw.html</tvar> (<tvar name=1>builder</tvar>) node to the current <tvar name=3>mw.html</tvar> instance. If a nil parameter is passed, this is a no-op. A (<tvar name=2>builder</tvar>) node is a string representation of an html element.
</translate>
mw.html:wikitext
html:wikitext( ... )
<translate> Appends an undetermined number of wikitext strings to the <tvar name=1>mw.html</tvar> object.
Note that this stops at the first nil item. </translate>
<translate> Basic wikitext will get parsed, like HTML, links, bold, lists or tables. However, templates and parser functions won't be evaluated if they are passed directly to this function, unless they came from template parameters.</translate> <translate> Those will be rendered in plain text instead.</translate> <translate> To evaluate them, they'll have to be passed through <tvar name=2>frame:preprocess</tvar>.</translate>
mw.html:newline
html:newline()
<translate> Appends a newline to the <tvar name=1>mw.html</tvar> object.</translate> <translate> Useful when used before and after <tvar name=2>mw.html:wikitext()</tvar>, when the wikitext contains lists or tables, whose syntax only has a special meaning when present at the start of a line.</translate>
mw.html:tag
html:tag( tagName, args )
<translate>
Appends a new child node with the given <tvar name=1>tagName</tvar> to the builder, and returns a <tvar name=2>mw.html</tvar> instance representing that new node. The <tvar name=3>args</tvar> parameter is identical to that of <tvar name=4>mw.html.create</tvar>
</translate>
<translate> Note that contrarily to other methods such as <tvar name=1>html:node()</tvar>, this method doesn't return the current <tvar name=2>mw.html</tvar> instance, but the <tvar name=2>mw.html</tvar> instance of the newly inserted tag.</translate>
<translate> Make sure to use <tvar name=2>html:done()</tvar> to go up to the parent <tvar name=1>mw.html</tvar> instance, or <tvar name=3>html:allDone()</tvar> if you have nested tags on several levels.</translate>
mw.html:attr
html:attr( name, value )
html:attr( table )
<translate>
Set an HTML attribute with the given <tvar name=1>name</tvar> and <tvar name=2>value</tvar> 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.
</translate>
mw.html:getAttr
html:getAttr( name )
<translate>
Get the value of a html attribute previously set using <tvar name=2>html:attr()</tvar> with the given <tvar name=1>name</tvar>.
</translate>
mw.html:addClass
html:addClass( class )
<translate> Adds a class name to the node's class attribute. If a nil parameter is passed, this is a no-op. </translate>
mw.html:css
html:css( name, value )
html:css( table )
<translate>
Set a CSS property with the given <tvar name=1>name</tvar> and <tvar name=2>value</tvar> 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.
</translate>
mw.html:cssText
html:cssText( css )
<translate>
Add some raw <tvar name=1>css</tvar> to the node's style attribute. If a nil parameter is passed, this is a no-op.
</translate>
mw.html:done
html:done()
<translate> Returns the parent node under which the current node was created. Like <tvar name=1>jQuery.end</tvar>, this is a convenience function to allow the construction of several child nodes to be chained together into a single statement. </translate>
mw.html:allDone
html:allDone()
<translate>
Like <tvar name=1>html:done()</tvar>, but traverses all the way to the root node of the tree and returns it.
Language library
Language codes are described at [[<tvar name=link>Special:MyLanguage/Language code</tvar>|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. </translate>
Template:Anchor
<translate>
Functions documented as <tvar name=1>mw.language.name</tvar> are available on the global <tvar name=2>mw.language</tvar> table; functions documented as <tvar name=3>mw.language:name</tvar> and <tvar name=4>lang:name</tvar> are methods of a language object (see <tvar name=5>mw.language.new</tvar> or <tvar name=6>mw.language.getContentLanguage</tvar>).
</translate>
mw.language.fetchLanguageName
mw.language.fetchLanguageName( code, inLanguage )
<translate> 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 <tvar name="param">inLanguage</tvar>. </translate>
mw.language.fetchLanguageNames
mw.language.fetchLanguageNames()
mw.language.fetchLanguageNames( inLanguage )
mw.language.fetchLanguageNames( inLanguage, include )
<translate> 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 <tvar name="param">inLanguage</tvar> returns all names in that language.
By default, only language names known to MediaWiki are returned; passing <tvar name="val1">'all'</tvar> for <tvar name="param">include</tvar> will return all available languages (from <tvar name=1>Template:Ll</tvar>), while passing <tvar name="val2">'mwfile'</tvar> will include only languages having customized messages included with MediaWiki core or enabled extensions. To explicitly select the default, <tvar name="val3">'mw'</tvar> may be passed.
</translate>
mw.language.getContentLanguage
mw.language.getContentLanguage()
mw.getContentLanguage()
<translate> Returns a new language object for the wiki's default content language. </translate>
mw.language.getFallbacksFor

mw.language.getFallbacksFor( code )
<translate> Returns a list of MediaWiki's fallback language codes for the specified code. </translate>
mw.language.isKnownLanguageTag
mw.language.isKnownLanguageTag( code )
<translate> Returns <tvar name=1>Template:Luai</tvar> 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 <tvar name=1>Template:Luai</tvar> for <tvar name=2>mw.language.isValidBuiltInCode</tvar>) and returns a non-empty string for <tvar name=3>mw.language.fetchLanguageName</tvar>.
</translate>
mw.language.isSupportedLanguage
mw.language.isSupportedLanguage( code )
<translate> Checks whether any localisation is available for that language code in MediaWiki.
A language code is "supported" if it is a "valid" code (returns <tvar name=1>Template:Luai</tvar> for <tvar name=2>mw.language.isValidCode</tvar>), 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 <tvar name=1>Template:Luai</tvar> for <tvar name=2>mw.language.isKnownLanguageTag</tvar>). Also note that certain codes are "supported" despite <tvar name=3>mw.language.isValidBuiltInCode</tvar> returning <tvar name=4>Template:Luai</tvar>.
</translate>
mw.language.isValidBuiltInCode
mw.language.isValidBuiltInCode( code )
<translate> Returns <tvar name=1>Template:Luai</tvar> 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 <tvar name=1>Template:Luai</tvar> for <tvar name=2>mw.language.isValidCode</tvar>); consists of only ASCII letters, numbers, and hyphens; and is at least two characters long.
Note that some codes are "supported" (i.e. returning <tvar name=1>Template:Luai</tvar> from <tvar name=2>mw.language.isSupportedLanguage</tvar>) even though this function returns <tvar name=3>Template:Luai</tvar>.
</translate>
mw.language.isValidCode
mw.language.isValidCode( code )
<translate> Returns <tvar name=1>Template:Luai</tvar> 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. </translate>
mw.language.new
mw.language.new( code )
mw.getLanguage( code )
<translate> 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 of 200 on the number of distinct language codes that may be used on a page. Exceeding this limit will result in errors. </translate>
mw.language:getCode
lang:getCode()
<translate> Returns the language code for this language object. </translate>
mw.language:toBcp47Code
lang:toBcp47Code()
<translate>
Returns the standard BCP-47 language code for this language object. This is the code string which is appropriate to use in HTML, for example as the value of a <tvar name="attr">lang</tvar> attribute.
</translate>
mw.language:getFallbackLanguages
lang:getFallbackLanguages()
<translate>
Returns a list of MediaWiki's fallback language codes for this language object. Equivalent to <tvar name="code">mw.language.getFallbacksFor( lang:getCode() )</tvar>.
</translate>
mw.language:isRTL
lang:isRTL()
<translate> Returns <tvar name=1>Template:Luai</tvar> if the language is written right-to-left, <tvar name=2>Template:Luai</tvar> if it is written left-to-right. </translate>
mw.language:lc
lang:lc( s )
<translate> Converts the string to lowercase, honoring any special rules for the given language.
When the [[<tvar name=anchor1>#Ustring library</tvar>|Ustring library]] is loaded, the <tvar name=1>mw.ustring.lower()</tvar> function is implemented as a call to <tvar name="code">mw.language.getContentLanguage():lc( s )</tvar>.
</translate>
mw.language:lcfirst
lang:lcfirst( s )
<translate>
Converts the first character of the string to lowercase, as with <tvar name=1>lang:lc()</tvar>.
</translate>
mw.language:uc
lang:uc( s )
<translate> Converts the string to uppercase, honoring any special rules for the given language.
When the [[<tvar name=anchor1>#Ustring library</tvar>|Ustring library]] is loaded, the <tvar name=1>mw.ustring.upper()</tvar> function is implemented as a call to <tvar name="code">mw.language.getContentLanguage():uc( s )</tvar>.
</translate>
mw.language:ucfirst
lang:ucfirst( s )
<translate> Converts the first character of the string to uppercase, as with <tvar name=1>lang:uc()</tvar>. </translate>
mw.language:caseFold
lang:caseFold( s )
<translate> Converts the string to a representation appropriate for case-insensitive comparison. Note that the result may not make any sense when displayed. </translate>
mw.language:formatNum
lang:formatNum( n )
lang:formatNum( n, options )
<translate> Formats a number with grouping and decimal separators appropriate for the given language. Given <tvar name=1>123456.78</tvar>, this may produce <tvar name=2>"123,456.78"</tvar>, <tvar name=3>"123.456,78"</tvar>, or even something like <tvar name=4>"١٢٣٬٤٥٦٫٧٨"</tvar> depending on the language and wiki configuration.
The <tvar name=1>options</tvar> is a table of options, which can be:
- <tvar name=1>
noCommafy</tvar>: Set <tvar name=3>Template:Luai</tvar> to omit grouping separators and use a dot (<tvar name=2>.</tvar>) as the decimal separator.</translate> <translate> Digit transformation may still occur, which may include transforming the decimal separator.</translate>
mw.language:formatDate
lang:formatDate( format, timestamp, local )
<translate>
Formats a date according to the given format string. If <tvar name=1>timestamp</tvar> is omitted, the default is the current time. The value for <tvar name=2>local</tvar> must be a boolean or nil; if <tvar name=3>Template:Luai</tvar>, the time is formatted in the [[<tvar name=help>Special:MyLanguage/Manual:$wgLocaltimezone</tvar>|wiki's local time]] rather than in UTC.
</translate>
<translate> The format string and supported values for <tvar name=1>timestamp</tvar> are identical to those for the [[<tvar name=2>Special:MyLanguage/Help:Extension:ParserFunctions#.23time</tvar>|#time parser function]] from <tvar name=3>Template:Ll</tvar>.</translate>
<translate> 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:</translate>
-- <translate nowrap><!--T:1917--> This string literal contains a newline, not the two characters <tvar name=2>"\n"</tvar>, so it is not equivalent to <tvar name=1>{{#time:\n}}</tvar>.</translate>
lang:formatDate( '\n' )
-- <translate nowrap><!--T:1918--> This is equivalent to <tvar name=1>{{#time:\n}}</tvar>, not <tvar name=2>{{#time:\\n}}</tvar>.</translate>
lang:formatDate( '\\n' )
-- <translate nowrap><!--T:1919--> This is equivalent to <tvar name=1>{{#time:\\n}}</tvar>, not <tvar name=2>{{#time:\\\\n}}</tvar>.</translate>
lang:formatDate( '\\\\n' )
mw.language:formatDuration
lang:formatDuration( seconds )
lang:formatDuration( seconds, chosenIntervals )
<translate> 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.
<tvar name=1>chosenIntervals</tvar>, if given, is a table with values naming the interval units to use in the response. These include <tvar name=2>'millennia'</tvar>, <tvar name=3>'centuries'</tvar>, <tvar name=4>'decades'</tvar>, <tvar name=5>'years'</tvar>, <tvar name=6>'weeks'</tvar>, <tvar name=7>'days'</tvar>, <tvar name=8>'hours'</tvar>, <tvar name=9>'minutes'</tvar>, and <tvar name=10>'seconds'</tvar>.
</translate>
mw.language:parseFormattedNumber
lang:parseFormattedNumber( s )
<translate>
This takes a number as formatted by <tvar name=1>lang:formatNum()</tvar> and returns the actual number. In other words, this is basically a language-aware version of <tvar name=2>tonumber()</tvar>.
</translate>
mw.language:convertPlural
Template:Anchor
lang:convertPlural( n, ... )
lang:convertPlural( n, forms )
lang:plural( n, ... )
lang:plural( n, forms )
<translate>
This chooses the appropriate grammatical form from <tvar name=1>forms</tvar> (which must be a [[<tvar name=anchor>#sequence</tvar>|sequence]] table) or <tvar name=2>...</tvar> based on the number <tvar name=3>n</tvar>. For example, in English you might use <tvar name=4>n .. ' ' .. lang:plural( n, 'sock', 'socks' )</tvar> or <tvar name=5>n .. ' ' .. lang:plural( n, { 'sock', 'socks' } )</tvar> to generate grammatically-correct text whether there is only 1 sock or 200 socks.
The necessary values for the sequence are language-dependent, see [[<tvar name=help>Special:MyLanguage/Help:Magic words#Localization</tvar>|localization of magic words]] and [[<tvar name=translatewiki>translatewiki:Special:MyLanguage/FAQ#PLURAL</tvar>|translatewiki's FAQ on PLURAL]] for some details. </translate>
mw.language:convertGrammar
Template:Anchor
lang:convertGrammar( word, case )
lang:grammar( case, word )
<translate>
- Note the different parameter order between the two aliases. <tvar name=3>
convertGrammar</tvar> matches the order of the method of the same name on MediaWiki's Language object, while <tvar name=2>grammar</tvar> matches the order of the parser function of the same name, documented at [[<tvar name=1>Special:MyLanguage/Help:Magic words#Localisation</tvar>|Help:Magic words#Localisation]].
This chooses the appropriate inflected form of <tvar name=1>word</tvar> for the given inflection code <tvar name=2>case</tvar>.
The possible values for <tvar name=1>word</tvar> and <tvar name=2>case</tvar> are language-dependent, see [[<tvar name=help>Special:MyLanguage/Help:Magic words#Localisation</tvar>]] and [[<tvar name=4>translatewiki:Special:MyLanguage/Grammar|translatewiki</tvar>:Grammar]] for some details.
</translate>
mw.language:gender
lang:gender( what, masculine, feminine, neutral )
lang:gender( what, { masculine, feminine, neutral } )
<translate>
Chooses the string corresponding to the gender of <tvar name=1>what</tvar>, which may be "male", "female", or a registered user name.
</translate>
mw.language:getArrow
lang:getArrow( direction )
<translate>
Returns a Unicode arrow character corresponding to direction:
- forwards: Either "→" or "←" depending on the directionality of the language.
- backwards: Either "←" or "→" depending on the directionality of the language.
- left: "←"
- right: "→"
- up: "↑"
- down: "↓"
</translate>
mw.language:getDir
lang:getDir()
<translate> Returns "ltr" or "rtl", depending on the directionality of the language. </translate>
mw.language:getDirMark
lang:getDirMark( opposite )
<translate>
Returns a string containing either <tvar name=1>U+200E</tvar> (the left-to-right mark) or <tvar name=2>U+200F</tvar> (the right-to-left mark), depending on the directionality of the language and whether opposite is a true or false value.
</translate>
mw.language:getDirMarkEntity
lang:getDirMarkEntity( opposite )
<translate>
Returns "<tvar name=1>‎</tvar>" or "<tvar name=2>‏</tvar>", depending on the directionality of the language and whether opposite is a true or false value.
</translate>
mw.language:getDurationIntervals
lang:getDurationIntervals( seconds )
lang:getDurationIntervals( seconds, chosenIntervals )
<translate> 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.
<tvar name=1>chosenIntervals</tvar>, if given, is a table with values naming the interval units to use in the response. These include <tvar name=2>'millennia'</tvar>, <tvar name=3>'centuries'</tvar>, <tvar name=4>'decades'</tvar>, <tvar name=5>'years'</tvar>, <tvar name=6>'weeks'</tvar>, <tvar name=7>'days'</tvar>, <tvar name=8>'hours'</tvar>, <tvar name=9>'minutes'</tvar>, and <tvar name=10>'seconds'</tvar>.
Those unit keywords are also the keys used in the response table. Only units with a non-zero value are set in the response, unless the response would be empty in which case the smallest unit is returned with a value of 0.
Message library
This library is an interface to the localisation messages and the MediaWiki: namespace. </translate>
Template:Anchor
<translate>
Functions documented as <tvar name=1>mw.message.name</tvar> are available on the global <tvar name=2>mw.message</tvar> table; functions documented as <tvar name=3>mw.message:name</tvar> and <tvar name=4>msg:name</tvar> are methods of a message object (see <tvar name=5>mw.message.new</tvar>).
</translate>
mw.message.new
mw.message.new( key, ... )
<translate> Creates a new message object for the given message <tvar name=1>key</tvar>.</translate>
<translate> The remaining parameters are passed to the new object's <tvar name=1>params()</tvar> method.</translate>
<translate> The message object has no properties, but has several methods documented below. </translate>
mw.message.newFallbackSequence
mw.message.newFallbackSequence( ... )
<translate> 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. </translate>
mw.message.newRawMessage
mw.message.newRawMessage( msg, ... )
<translate>
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 <tvar name=1>params()</tvar> method.
The message object has no properties, but has several methods documented below. </translate>
mw.message.rawParam
mw.message.rawParam( value )
<translate>
Wraps the value so that it will not be parsed as wikitext by <tvar name=1>msg:parse()</tvar>.
</translate>
mw.message.numParam
mw.message.numParam( value )
<translate>
Wraps the value so that it will automatically be formatted as by <tvar name=1>lang:formatNum()</tvar>. Note this does not depend on the [[<tvar name=anchor2>#Language library</tvar>|Language library]] actually being available.
</translate>
mw.message.getDefaultLanguage
mw.message.getDefaultLanguage()
<translate> Returns a Language object for the default language. </translate>
mw.message:params
msg:params( ... )
msg:params( params )
<translate> Add parameters to the message, which may be passed as individual arguments or as a [[<tvar name=anchor1>#sequence</tvar>|sequence]] table. Parameters must be numbers, strings, or the special values returned by <tvar name=1>mw.message.numParam()</tvar> or <tvar name=2>mw.message.rawParam()</tvar>. If a sequence table is used, parameters must be directly present in the table; references using the <tvar name=3>__index metamethod</tvar> will not work.
Returns the <tvar name=1>msg</tvar> object, to allow for call chaining.
</translate>
mw.message:rawParams
msg:rawParams( ... )
msg:rawParams( params )
<translate> Like <tvar name=1>:params()</tvar>, but has the effect of passing all the parameters through <tvar name=2>mw.message.rawParam()</tvar> first.
Returns the <tvar name=1>msg</tvar> object, to allow for call chaining.
</translate>
mw.message:numParams
msg:numParams( ... )
msg:numParams( params )
<translate> Like <tvar name=1>:params()</tvar>, but has the effect of passing all the parameters through <tvar name=2>mw.message.numParam()</tvar> first.
Returns the <tvar name=1>msg</tvar> object, to allow for call chaining.
</translate>
mw.message:inLanguage
msg:inLanguage( lang )
<translate>
Specifies the language to use when processing the message. <tvar name=1>lang</tvar> may be a string or a table with a <tvar name=2>getCode()</tvar> method (i.e. a [[<tvar name=anchor>#Language library</tvar>|Language object]]).
The default language is the one returned by <tvar name=1>mw.message.getDefaultLanguage()</tvar>.
Returns the <tvar name=1>msg</tvar> object, to allow for call chaining.
</translate>
mw.message:useDatabase
msg:useDatabase( bool )
<translate> 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 <tvar name=1>Template:Luai</tvar>.
Returns the <tvar name=1>msg</tvar> object, to allow for call chaining.
</translate>
mw.message:plain
msg:plain()
<translate> Substitutes the parameters and returns the message wikitext as-is. Template calls and parser functions are intact. </translate>
mw.message:exists
msg:exists()
<translate> Returns a boolean indicating whether the message key exists. </translate>
mw.message:isBlank
msg:isBlank()
<translate> Returns a boolean indicating whether the message key has content. Returns <tvar name=1>Template:Luai</tvar> if the message key does not exist or the message is the empty string. </translate>
mw.message:isDisabled
msg:isDisabled()
<translate> Returns a boolean indicating whether the message key is disabled. Returns <tvar name=1>Template:Luai</tvar> if the message key does not exist or if the message is the empty string or the string <tvar name=2>"-"</tvar>.
Site library
</translate>
mw.site.currentVersion
<translate> A string holding the current version of MediaWiki. </translate>
mw.site.scriptPath
<translate> The value of <tvar name=1>Template:Wg</tvar>. </translate>
mw.site.server
<translate> The value of <tvar name=1>Template:Wg</tvar>. </translate>
mw.site.siteName
<translate> The value of <tvar name=1>Template:Wg</tvar>. </translate>
mw.site.stylePath
<translate> The value of <tvar name=1>Template:Wg</tvar>. </translate>
mw.site.namespaces
<translate> Table holding data for all namespaces, indexed by number.
The data available is: </translate>
- id: <translate> Namespace number.</translate>
- name: <translate> Local namespace name.</translate>
- canonicalName: <translate> Canonical namespace name.</translate>
- displayName: <translate> Set on namespace 0, the name to be used for display (since the name is often the empty string).</translate>
- hasSubpages: <translate> Whether subpages are enabled for the namespace.</translate>
- hasGenderDistinction: <translate> Whether the namespace has different aliases for different genders.</translate>
- isCapitalized: <translate> Whether the first letter of pages in the namespace is capitalized.</translate>
- isContent: <translate> Whether this is a content namespace.</translate>
- isIncludable: <translate> Whether pages in the namespace can be transcluded.</translate>
- isMovable: <translate> Whether pages in the namespace can be moved.</translate>
- isSubject: <translate> Whether this is a subject namespace.</translate>
- isTalk: <translate> Whether this is a talk namespace.</translate>
- defaultContentModel: <translate> The default content model for the namespace, as a string.</translate>
- aliases: <translate> List of aliases for the namespace.</translate>
- subject: <translate> Reference to the corresponding subject namespace's data.</translate>
- talk: <translate> Reference to the corresponding talk namespace's data.</translate>
- associated: <translate>
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 <tvar name=1>mw.site.namespaces[4]</tvar> and <tvar name=2>mw.site.namespaces.Project</tvar> will return information about the Project namespace.
</translate>
mw.site.contentNamespaces
<translate> Table holding just the content namespaces, indexed by number. See <tvar name=1>mw.site.namespaces</tvar> for details. </translate>
mw.site.subjectNamespaces
<translate> Table holding just the subject namespaces, indexed by number. See <tvar name=1>mw.site.namespaces</tvar> for details. </translate>
mw.site.talkNamespaces
<translate> Table holding just the talk namespaces, indexed by number. See <tvar name=1>mw.site.namespaces</tvar> for details. </translate>
mw.site.stats
<translate> Table holding site statistics. Available statistics are: </translate>
- pages: <translate> Number of pages in the wiki.</translate>
- articles: <translate> Number of articles in the wiki.</translate>
- files: <translate> Number of files in the wiki.</translate>
- edits: <translate> Number of edits in the wiki.</translate>
- users: <translate> Number of users in the wiki.</translate>
- activeUsers: <translate> Number of active users in the wiki.</translate>
- admins: <translate> Number of users in group 'sysop' in the wiki.</translate>
mw.site.stats.pagesInCategory
mw.site.stats.pagesInCategory( <translate> category, which</translate> )
<translate>
Gets statistics about the category. If which has the special value <tvar name=1>"*"</tvar>, the result is a table with the following properties:
</translate>
- all: <translate> Total pages, files, and subcategories.</translate>
- subcats: <translate> Number of subcategories.</translate>
- files: <translate> Number of files.</translate>
- pages: <translate> Number of pages.</translate>
<translate>
If which is one of the above keys (<tvar name=1>"all", "subcats", "files", "pages"</tvar>), the result is a number with the corresponding value.
Each new category queried will increment the expensive function count. </translate>
mw.site.stats.pagesInNamespace
mw.site.stats.pagesInNamespace( <translate> namespace</translate> )
<translate> Returns the number of pages in the given namespace (specify by number). </translate>
mw.site.stats.usersInGroup
mw.site.stats.usersInGroup( <translate> group</translate> )
<translate> Returns the number of users in the given group. </translate>
mw.site.interwikiMap
mw.site.interwikiMap( <translate> filter</translate> )
<translate>
Returns a table holding data about available [[<tvar name=help>Special:MyLanguage/Manual:Interwiki</tvar>|interwiki]] prefixes. If filter is the string <tvar name=1>"local"</tvar>, then only data for local interwiki prefixes is returned. If filter is the string <tvar name=2>"!local"</tvar>, then only data for non-local prefixes is returned. If no filter is specified, data for all prefixes is returned. A <tvar name=1>"local"</tvar> 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: </translate>
- prefix - <translate> the interwiki prefix.</translate>
- url - <translate> the URL that the interwiki points to. The page name is represented by the parameter $1.</translate>
- isProtocolRelative - <translate> a boolean showing whether the URL is protocol-relative.</translate>
- isLocal - <translate> whether the URL is for a site in the current project.</translate>
- isCurrentWiki - <translate> whether the URL is for the current wiki.</translate>
- isTranscludable - <translate> whether pages using this interwiki prefix are <tvar name=1>transcludable</tvar>. This requires [[<tvar name=help2>Special:MyLanguage/Manual:$wgEnableScaryTranscluding</tvar>|scary transclusion]], which is disabled on Wikimedia wikis.</translate>
- isExtraLanguageLink - <translate> whether the interwiki is listed in <tvar name=1>Template:Wg</tvar>.</translate>
- displayText - <translate> for links listed in <tvar name=1>$wgExtraInterlanguageLinkPrefixes</tvar>, this is the display text shown for the interlanguage link. Nil if not specified.</translate>
- tooltip - <translate>
for links listed in <tvar name=1>$wgExtraInterlanguageLinkPrefixes</tvar>, 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 [[<tvar name=anchor1>#String library</tvar>|String library]] and the [[<tvar name=anchor2>#Ustring library</tvar>|Ustring library]]. These functions are safe for use with UTF-8 strings. </translate>
mw.text.decode
mw.text.decode( <translate> string</translate> )
mw.text.decode( <translate> string, decodeNamedEntities</translate> )
<translate> Replaces HTML entities in the string with the corresponding characters. </translate>
<translate> If boolean <tvar name=1>decodeNamedEntities</tvar> is omitted or false, the only named entities recognized are <tvar name=5>< (<), > (>), & (&), " ("</tvar>) and <tvar name=6> </tvar> (the non-breaking space, <tvar name=7>U+00A0</tvar>).</translate>
<translate> Otherwise, the list of HTML5 named entities to recognize is loaded from PHP's <tvar name=1>get_html_translation_table</tvar> function.</translate>
<translate> Template:Red: Approximately 600 of around <tvar name=1>2,200</tvar> named entities in the HTML5 standard do not get decoded, even when <tvar name=2>decodeNamedEntities</tvar> is used; this includes approximately 40 of around 250 entities which are also included in HTML4.</translate>
<translate> This occurs because PHP's <tvar name=1>get_html_translation_table</tvar> function returns only one mapping for each character, so for example <tvar name=2>Template:Code</tvar> is not decoded since PHP returns only <tvar name=3>Template:Code</tvar> as the mapping for <tvar name=4>Template:Code</tvar>.</translate>
mw.text.encode
mw.text.encode( <translate> string</translate> )
mw.text.encode( <translate> string, charset</translate> )
<translate> Replaces characters in a string with HTML entities.</translate>
<translate> Five characters are replaced with the appropriate named entities: <tvar name=1><</tvar>, <tvar name=2>></tvar>, <tvar name=3>&</tvar>, <tvar name=4>"</tvar> and the non-breaking space (<tvar name=5>U+00A0</tvar>).</translate>
<translate> All others are replaced with numeric entities.</translate>
<translate>
If <tvar name=4>charset</tvar> is supplied, it should be a string as appropriate to go inside brackets in a [[<tvar name=anchor>#Ustring patterns</tvar>|Ustring pattern]], i.e. the "set" in <tvar name=1>[set]</tvar>. The default charset contains six characters: <tvar name=2><, >, &, ", '</tvar> and the non-breaking space (<tvar name=3>U+00A0</tvar>).
</translate>
mw.text.jsonDecode
mw.text.jsonDecode( <translate> string</translate> )
mw.text.jsonDecode( <translate> string, flags</translate> )
<translate>
Decodes a JSON string. <tvar name=4>flags</tvar> is 0 or a combination (use <tvar name=1>+</tvar>) of the flags <tvar name=2>mw.text.JSON_PRESERVE_KEYS</tvar> and <tvar name=3>mw.text.JSON_TRY_FIXING</tvar>.
Normally JSON's zero-based arrays are renumbered to Lua one-based sequence tables; to prevent this, pass <tvar name=1>mw.text.JSON_PRESERVE_KEYS</tvar>.
To relax certain requirements in JSON, such as no terminal comma in arrays or objects, pass <tvar name=1>mw.text.JSON_TRY_FIXING</tvar>. 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 <tvar name=1>
mw.text.JSON_PRESERVE_KEYS</tvar> is used.
</translate>
mw.text.jsonEncode
mw.text.jsonEncode( <translate> value</translate> )
mw.text.jsonEncode( <translate> value, flags</translate> )
<translate>
Encode a JSON string. Errors are raised if the passed value cannot be encoded in JSON. <tvar name=4>flags</tvar> is 0 or a combination (use <tvar name=1>+</tvar>) of the flags <tvar name=2>mw.text.JSON_PRESERVE_KEYS</tvar> and <tvar name=3>mw.text.JSON_PRETTY</tvar>.
Normally Lua one-based sequence tables are encoded as JSON zero-based arrays; when <tvar name=1>mw.text.JSON_PRESERVE_KEYS</tvar> is set in <tvar name=2>flags</tvar>, zero-based sequence tables are encoded as JSON arrays.
Limitations:
- Empty tables are always encoded as empty arrays (<tvar name=1>
[]</tvar>), not empty objects (<tvar name=2>{}</tvar>). - 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 <tvar name=3>
__pairs</tvar> 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 <tvar name=4>
mw.text.JSON_PRESERVE_KEYS</tvar> is used. - When both a number and the string representation of that number are used as keys in the same table, behavior is unspecified.
</translate>
mw.text.killMarkers
mw.text.killMarkers( <translate> string</translate> )
<translate> Removes all MediaWiki [[<tvar name=1>strip marker</tvar>|strip marker]]s from a string. </translate>
mw.text.listToText
mw.text.listToText( <translate> list</translate> )
mw.text.listToText( <translate> list, separator, conjunction</translate> )
<translate>
Joins a list, prose-style. In other words, it's like <tvar name=1>table.concat()</tvar> but with a different separator before the final item.
The default separator is taken from <tvar name=1>MediaWiki:comma-separator</tvar> in the wiki's content language, and the default conjunction is <tvar name=2>MediaWiki:and</tvar> concatenated with <tvar name=3>MediaWiki:word-separator</tvar>.
Examples, using the default values for the messages: </translate>
-- <translate nowrap><!--T:2048--> Returns the empty string</translate>
mw.text.listToText( {} )
-- <translate nowrap><!--T:2049--> Returns "1"</translate>
mw.text.listToText( { 1 } )
-- <translate nowrap><!--T:2050--> Returns "1 and 2"</translate>
mw.text.listToText( { 1, 2 } )
-- <translate nowrap><!--T:2051--> Returns "1, 2, 3, 4 and 5"</translate>
mw.text.listToText( { 1, 2, 3, 4, 5 } )
-- <translate nowrap><!--T:2052--> Returns "1; 2; 3; 4 or 5"</translate>
mw.text.listToText( { 1, 2, 3, 4, 5 }, '; ', ' or ' )
mw.text.nowiki
mw.text.nowiki( <translate> string</translate> )
<translate> Replaces various characters in the string with HTML entities to prevent their interpretation as wikitext. This includes:
- The following characters: <tvar name=1>
",&,',<,=,>,[,],{,|,}</tvar></translate>
<translate>
- The following characters at the start of the string or immediately after a newline: <tvar name=2>
#,*,:,;, space, tab (\t)</tvar></translate>
<translate>
- Blank lines will have one of the associated newline or carriage return characters escaped</translate>
<translate>
- <tvar name=3>
----</tvar> at the start of the string or immediately after a newline will have the first <tvar name=4>-</tvar> escaped</translate>
<translate>
- <tvar name=5>
__</tvar> will have one underscore escaped</translate>
<translate>
- <tvar name=6>
://</tvar> will have the colon escaped</translate>
<translate>
- A whitespace character following <tvar name=7>
ISBN,RFC</tvar>, or <tvar name=8>PMID</tvar> will be escaped</translate>
mw.text.split
mw.text.split( <translate> string, pattern, plain</translate> )
<translate>
Splits the string into substrings at boundaries matching the [[<tvar name=anchor1>#Ustring patterns</tvar>|Ustring pattern]] <tvar name=3>pattern</tvar>. If <tvar name=4>plain</tvar> is specified and <tvar name=1>Template:Luai</tvar>, <tvar name=3>pattern</tvar> will be interpreted as a literal string rather than as a Lua pattern (just as with the parameter of the same name for <tvar name=2>mw.ustring.find()</tvar>). Returns a table containing the substrings.
For example, <tvar name=1>mw.text.split( 'a b\tc\nd', '%s' )</tvar> would return a table <tvar name=2>{ 'a', 'b', 'c', 'd' }</tvar>.
If <tvar name=1>pattern</tvar> matches the empty string, <tvar name=2>string</tvar> will be split into individual characters.
Note that this function can be over 60 times slower than a reimplementation that is not Unicode-aware, such as the following: </translate>
function split(text, pattern, plain)
local ret = {}
local s, l = 1, string.len( text )
while s do
local e, n = string.find( text, pattern, s, plain )
if not e then
ret[#ret+1] = string.sub ( text, s )
s = nil
elseif n < e then
-- Empty separator!
ret[#ret+1] = string.sub ( text, s, e )
if e < l then
s = e + 1
else
s = nil
end
else
ret[#ret+1] = e > s and string.sub( text, s, e - 1 ) or ''
s = n + 1
end
end
return ret
end
mw.text.gsplit
mw.text.gsplit( <translate> string, pattern, plain</translate> )
<translate>
Returns an [[<tvar name=anchor1>#iterators</tvar>|iterator function]] that will iterate over the substrings that would be returned by the equivalent call to <tvar name=1>mw.text.split()</tvar>.
Note that this function can be over 60 times slower than a reimplementation that is not Unicode-aware, such as the following: </translate>
function gsplit( text, pattern, plain )
local s, l = 1, string.len( text )
return function ()
if s then
local e, n = string.find( text, pattern, s, plain )
local ret
if not e then
ret = string.sub( text, s )
s = nil
elseif n < e then
-- Empty separator!
ret = string.sub( text, s, e )
if e < l then
s = e + 1
else
s = nil
end
else
ret = e > s and string.sub( text, s, e - 1 ) or ''
s = n + 1
end
return ret
end
end, nil, nil
end
mw.text.tag
mw.text.tag( <translate> name, attrs, content</translate> )
mw.text.tag{ <translate> name = string, attrs = table, content = string|false</translate> }
<translate>
- Note the use of [[<tvar name=1>#named arguments</tvar>|named arguments]].
Generates an HTML-style tag for name.
If <tvar name=3>attrs</tvar> is given, it must be a table with string keys. String and number values are used as the value of the attribute; boolean <tvar name=1>Template:Luai</tvar> results in the key being output as an HTML5 valueless parameter; boolean <tvar name=2>Template:Luai</tvar> skips the key entirely; and anything else is an error.
If <tvar name=3>content</tvar> is not given (or is nil), only the opening tag is returned. If <tvar name=3>content</tvar> is boolean <tvar name=1>Template:Luai</tvar>, 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 <tvar name=2>mw.text.encode()</tvar> if needed.
For properly returning extension tags such as <tvar name=1>Template:Tag</tvar>, use <tvar name=2>frame:extensionTag()</tvar> instead. </translate>
mw.text.trim
mw.text.trim( <translate> string</translate> )
mw.text.trim( <translate> string, charset</translate> )
<translate> Remove whitespace or other characters from the beginning and end of a string.
If <tvar name=5>charset</tvar> is supplied, it should be a string as appropriate to go inside brackets in a [[<tvar name=anchor>#Ustring patterns</tvar>|Ustring pattern]], i.e. the <tvar name=1>"set"</tvar> in <tvar name=2>[set]</tvar>. The default charset is ASCII whitespace, <tvar name=3>%s</tvar>, which is equivalent to <tvar name=4>"\t\r\n\f\v "</tvar>.
</translate>
mw.text.truncate
mw.text.truncate( <translate> text, length</translate> )
mw.text.truncate( <translate> text, length, ellipsis</translate> )
mw.text.truncate( <translate> text, length, ellipsis, adjustLength</translate> )
<translate>
Truncates <tvar name=2>text</tvar> to the specified length in code points, adding <tvar name=3>ellipsis</tvar> if truncation was performed. If length is positive, the end of the string will be truncated; if negative, the beginning will be removed. If <tvar name=4>adjustLength</tvar> is given and <tvar name=1>Template:Luai</tvar>, the resulting string including ellipsis will not be longer than the specified length.
The default value for <tvar name=2>ellipsis</tvar> is taken from <tvar name=1>MediaWiki:ellipsis</tvar> in the wiki's content language.
Examples, using the default <tvar name=1>"..."</tvar> ellipsis: </translate>
-- <translate nowrap><!--T:2483--> Returns "foobarbaz"</translate>
mw.text.truncate( "foobarbaz", 9 )
-- <translate nowrap><!--T:2484--> Returns "fooba..."</translate>
mw.text.truncate( "foobarbaz", 5 )
-- <translate nowrap><!--T:2485--> Returns "...arbaz"</translate>
mw.text.truncate( "foobarbaz", -5 )
-- <translate nowrap><!--T:2486--> Returns "foo..."</translate>
mw.text.truncate( "foobarbaz", 6, nil, true )
-- <translate nowrap><!--T:2487--> Returns "foobarbaz", because that's shorter than "foobarba..."</translate>
mw.text.truncate( "foobarbaz", 8 )
mw.text.unstripNoWiki
mw.text.unstripNoWiki( <translate> string</translate> )
<translate> Replaces MediaWiki <nowiki> [[<tvar name=1>strip marker</tvar>|strip marker]]s with the corresponding text. Other types of strip markers are not changed. </translate>
mw.text.unstrip
mw.text.unstrip( <translate> string</translate> )
<translate>
Equivalent to <tvar name=1>mw.text.killMarkers( mw.text.unstripNoWiki( string ))</tvar>.
This no longer reveals the HTML behind special page transclusion, <tvar name=1><ref></tvar> tags, and so on as it did in earlier versions of Scribunto.
Title library
</translate>
mw.title.equals
mw.title.equals( a, b )
<translate> Test for whether two titles are equal. Note that fragments are ignored in the comparison. </translate>
mw.title.compare
mw.title.compare( a, b )
<translate>
Returns <tvar name=1>-1, 0</tvar>, or <tvar name=2>1</tvar> to indicate whether the title <tvar name=3>a</tvar> is less than, equal to, or greater than title <tvar name=4>b</tvar>.
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 <tvar name=1><</tvar> operator.
</translate>
mw.title.getCurrentTitle
mw.title.getCurrentTitle()
<translate> Returns the title object for the current page. </translate>
mw.title.new
mw.title.new( <translate> text, namespace</translate> )
mw.title.new( ID )
<translate>
</translate>
<translate> Creates a new title object.</translate>
<translate>
If a number <tvar name=1>ID</tvar> is given, an object is created for the title with that <tvar name=2>page_id</tvar>. The title referenced will be counted as linked from the current page. If the <tvar name=2>page_id</tvar> 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 <tvar name=2>text</tvar> 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, <tvar name=3>namespace</tvar> (which may be any key found in <tvar name=1>mw.site.namespaces</tvar>) will be used. If the text is not a valid title, nil is returned.
</translate>
mw.title.makeTitle
mw.title.makeTitle( <translate> namespace, title, fragment, interwiki</translate> )
<translate>
Creates a title object with title <tvar name=2>title</tvar> in namespace <tvar name=3>namespace</tvar>, optionally with the specified <tvar name=4>fragment</tvar> and <tvar name=5>interwiki</tvar> prefix. <tvar name=3>namespace</tvar> may be any key found in <tvar name=1>mw.site.namespaces</tvar>. If the resulting title is not valid, returns nil.
Note that, unlike <tvar name=mw_title_new_function>mw.title.new()</tvar>, this method will always apply the specified namespace. For example, <tvar name=1>mw.title.makeTitle( 'Template', 'Module:Foo' )</tvar> will create an object for the page <tvar name=2>Template:Module:Foo</tvar>, while <tvar name=3>mw.title.new( 'Module:Foo', 'Template' )</tvar> will create an object for the page <tvar name=4>Module:Foo</tvar>.
Note also that functionality for interwiki titles is limited to <tvar name=1>interwiki / isExternal / isLocal</tvar> and URL-related methods; other methods might not behave as expected.
Title objects
A title object has a number of properties and methods. Most of the properties are read-only.
Note that fields ending with <tvar name=1>text</tvar> return titles as string values whereas the fields ending with <tvar name=2>title</tvar> return title objects.
- id: The <tvar name=1>page_id</tvar>. <tvar name=2>
0</tvar> if the page does not exist.</translate> Template:Red.
<translate>
- interwiki: The interwiki prefix, or the empty string if none.</translate>
<translate>
- namespace: The namespace number.</translate>
<translate>
- fragment: The fragment (aka section/anchor linking), or the empty string. May be assigned.</translate>
<translate>
- nsText: The text of the namespace for the page.</translate>
<translate>
- subjectNsText: The text of the subject namespace for the page.</translate>
<translate>
- talkNsText: The text of the talk namespace for the page, or <tvar name=1>
nil</tvar> if this title cannot have a talk page. (added in MediaWiki <tvar name=2>1.42.0-wmf.15</tvar>, refs <tvar name=3>T180911</tvar>)</translate>
<translate>
- text: The title of the page, without the namespace or interwiki prefixes.</translate>
<translate>
- prefixedText: The title of the page, with the namespace and interwiki prefixes.</translate>
<translate>
- fullText: The title of the page, with the namespace and interwiki prefixes and the fragment. Interwiki is not returned if equal to the current.</translate>
<translate>
- rootText: If this is a subpage, the title of the root page without prefixes. Otherwise, the same as <tvar name=1>
title.text</tvar>.</translate>
<translate>
- baseText: If this is a subpage, the title of the page it is a subpage of without prefixes. Otherwise, the same as <tvar name=1>
title.text</tvar>.</translate>
<translate>
- subpageText: If this is a subpage, just the subpage name. Otherwise, the same as <tvar name=1>
title.text</tvar>.</translate>
<translate>
- canTalk: Whether the page for this title could have a talk page.</translate>
<translate>
- exists: Whether the page exists. Alias for <tvar name=1>
file.exists</tvar> for Media-namespace titles. For File-namespace titles this checks the existence of the file description page, not the file itself. Template:Red.</translate>
<translate>
- file, fileExists: See [[<tvar name=1>#File metadata</tvar>|#File metadata]] below.</translate>
<translate>
- isContentPage: Whether this title is in a content namespace.</translate>
<translate>
- isExternal: Whether this title has an interwiki prefix.</translate>
<translate>
- 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.</translate>
<translate>
- isRedirect: Whether this is the title for a page that is a redirect. Template:Red.</translate>
<translate>
- isSpecialPage: Whether this is the title for a possible special page (i.e. a page in the Special: namespace).</translate>
<translate>
- isSubpage: Whether this title is a subpage of some other title.</translate>
<translate>
- isTalkPage: Whether this is a title for a talk page.</translate>
<translate>
- isSubpageOf( title2 ): Whether this title is a subpage of the given title.</translate>
<translate>
- inNamespace( ns ): Whether this title is in the given namespace. Namespaces may be specified by anything that is a key found in <tvar name=1>
mw.site.namespaces</tvar>.</translate>
<translate>
- inNamespaces( ... ): Whether this title is in any of the given namespaces. Namespaces may be specified by anything that is a key found in <tvar name=1>
mw.site.namespaces</tvar>.</translate>
<translate>
- 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 <tvar name=1>
mw.site.namespaces</tvar>.</translate>
<translate>
- contentModel: The content model for this title, as a string. For a page that does not exist, this is what content model it would receive upon creation. Template:Red.</translate>
<translate>
- basePageTitle: The same as <tvar name=1>
mw.title.makeTitle( title.namespace, title.baseText )</tvar>.</translate>
<translate>
- rootPageTitle: The same as <tvar name=1>
mw.title.makeTitle( title.namespace, title.rootText )</tvar>.</translate>
<translate>
- talkPageTitle: The same as <tvar name=1>
mw.title.makeTitle( mw.site.namespaces[title.namespace].talk.id, title.text )</tvar>, or <tvar name=2>nil</tvar> if this title cannot have a talk page.</translate>
<translate>
- subjectPageTitle: The same as <tvar name=1>
mw.title.makeTitle( mw.site.namespaces[title.namespace].subject.id, title.text )</tvar>.</translate>
<translate>
- redirectTarget: Returns a title object of the target of the redirect page if the page is a redirect and the page exists, returns <tvar name=1>Template:Luai</tvar> otherwise.</translate>
<translate>
- protectionLevels: The page's protection levels. This is a table with keys corresponding to each action (e.g., <tvar name=2>
"edit"</tvar> and <tvar name=3>"move"</tvar>). 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 <tvar name=1>nil</tvar>. Template:Red.</translate>
<translate>
- cascadingProtection: The cascading protections applicable to the page. This is a table with keys <tvar name=1>
"restrictions"</tvar> (itself a table with keys like <tvar name=2>protectionLevels</tvar> has) and <tvar name=3>"sources"</tvar> (an array listing titles where the protections cascade from). If no protections cascade to the page, <tvar name=1>"restrictions"</tvar> and <tvar name=3>"sources"</tvar> will be empty. Template:Red.</translate>
<translate>
- categories: (since <tvar name=1>v1.43.0-wmf.18</tvar>) The list of categories used on the page. Template:Red
- subPageTitle( text ): The same as <tvar name=2>
mw.title.makeTitle( title.namespace, title.text .. '/' .. text )</tvar>.</translate>
<translate>
- partialUrl(): Returns <tvar name=1>
title.text</tvar> encoded as it would be in a URL.</translate>
<translate>
- fullUrl( query, proto ): Returns the full URL (with optional query table/string) for this title. <tvar name=2>proto</tvar> may be specified to control the scheme of the resulting url: <tvar name=1>
"http","https"</tvar>, <tvar name=3>"relative"</tvar> (the default), or <tvar name=4>"canonical"</tvar>.</translate>
<translate>
- localUrl( query ): Returns the local URL (with optional query table/string) for this title.</translate>
<translate>
- canonicalUrl( query ): Returns the canonical URL (with optional query table/string) for this title.</translate>
<translate>
- content or getContent(): Returns the (unparsed) content of the page, or <tvar name=1>
nil</tvar> if there is no page. The page will be recorded as a transclusion.</translate>
<translate>
- pageLang: A [[<tvar name=anchor2>#Language library</tvar>|language object]] for the title's [[<tvar name=1>Special:MyLanguage/Manual:Language#Page content language</tvar>|page content language]], which defaults to the wiki's content language. Template:Red.</translate>
<translate>
Title objects may be compared using [[<tvar name=anchor1>#Relational operators</tvar>|relational operators]]. <tvar name=2>tostring( title )</tvar> will return <tvar name=1>title.prefixedText</tvar>.
Note that accessing any [[<tvar name=1>#Expensive properties</tvar>|expensive]] field on a title object records a "link" to the page (as shown on <tvar name=2>Special:WhatLinksHere</tvar>, for example). Using the title object's <tvar name=3>getContent()</tvar> method or accessing the <tvar name=4>redirectTarget</tvar> field records it as <tvar name=6>file</tvar> or <tvar name=7>fileExists</tvar> fields records it as a <tvar name=8>"Template:Int"</tvar>.
File metadata
Title objects representing a page in the File or Media namespace will have a property called <tvar name=1>file</tvar>. Template:Red This is a table, structured as follows:
- exists: Whether the file exists. It will be recorded as an image usage. The <tvar name=1>
fileExists</tvar> property on a Title object exists for backwards compatibility reasons and is an alias for this property. If this is <tvar name=2>Template:Luai</tvar>, all other file properties will be <tvar name=3>nil</tvar>.</translate>
<translate>
- width: The width of the file. If the file contains multiple pages, this is the width of the first page.</translate>
<translate>
- height: The height of the file. If the file contains multiple pages, this is the height of the first page.</translate>
<translate>
- pages: If the file format supports multiple pages, this is a table containing tables for each page of the file; otherwise, it is <tvar name=1>
nil</tvar>. The [[<tvar name=anchor>#Length operator</tvar>|# operator]] can be used to get the number of pages in the file. Each individual page table contains a width and height property.</translate>
<translate>
- size: The size of the file in bytes.</translate>
<translate>
- mimeType: The MIME type of the file.</translate>
<translate>
- length: The length (duration) of the media file in seconds. Zero for media types which do not support length.
Expensive properties
The properties <tvar name=1>id, isRedirect, exists</tvar>, and <tvar name=2>contentModel</tvar> require fetching data about the title from the database. For this reason, the [[<tvar name=help>Special:MyLanguage/Manual:$wgExpensiveParserFunctionLimit</tvar>|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.
URI library
</translate>
mw.uri.encode
mw.uri.encode( <translate> string, enctype</translate> )
<translate>
Percent-encodes the string. The default type, <tvar name=2>"QUERY"</tvar>, encodes spaces using <tvar name=3>'+'</tvar> for use in query strings; <tvar name=4>"PATH"</tvar> encodes spaces as <tvar name=5>%20</tvar>; and <tvar name=6>"WIKI"</tvar> encodes spaces as <tvar name=7>'_'</tvar>.
Note that the "WIKI" format is not entirely reversible, as both spaces and underscores are encoded as <tvar name=1>'_'</tvar>. </translate>
mw.uri.decode
mw.uri.decode( <translate> string, enctype</translate> )
<translate>
Percent-decodes the string. The default type, <tvar name=2>"QUERY"</tvar>, decodes <tvar name=3>'+'</tvar> to space; <tvar name=4>"PATH"</tvar> does not perform any extra decoding; and <tvar name=5>"WIKI"</tvar> decodes <tvar name=6>'_'</tvar> to space.
</translate>
mw.uri.anchorEncode
mw.uri.anchorEncode( <translate> string</translate> )
<translate> Encodes a string for use in a MediaWiki URI fragment. </translate>
mw.uri.buildQueryString
mw.uri.buildQueryString( <translate> table</translate> )
<translate> Encodes a table as a URI query string. Keys should be strings; values may be strings or numbers, sequence tables, or boolean false. </translate>
mw.uri.parseQueryString
mw.uri.parseQueryString( s, i, j )
<translate>
Decodes the query string <tvar name=1>s</tvar> to a table. Keys in the string without values will have a value of <tvar name=2>Template:Luai</tvar>; keys repeated multiple times will have sequence tables as values; and others will have strings as values.
The optional numerical arguments <tvar name=1>i</tvar> and <tvar name=2>j</tvar> can be used to specify a substring of <tvar name=3>s</tvar> to be parsed, rather than the entire string. <tvar name=1>i</tvar> is the position of the first character of the substring, and defaults to 1. <tvar name=2>j</tvar> is the position of the last character of the substring, and defaults to the length of the string. Both <tvar name=1>i</tvar> and <tvar name=2>j</tvar> can be negative, as in <tvar name=4>string.sub</tvar>.
</translate>
mw.uri.canonicalUrl
mw.uri.canonicalUrl( <translate> page, query</translate> )
<translate> Returns a [[<tvar name=1>#URI object</tvar>|URI object]] for the [[<tvar name=2>Special:MyLanguage/Help:Magic words#URL data</tvar>|canonical URL]] for a page, with optional query string/table. </translate>
mw.uri.fullUrl
mw.uri.fullUrl( <translate> page, query</translate> )
<translate> Returns a [[<tvar name=1>#URI object</tvar>|URI object]] for the [[<tvar name=2>Special:MyLanguage/Help:Magic words#URL data</tvar>|full URL]] for a page, with optional query string/table. </translate>
mw.uri.localUrl
mw.uri.localUrl( <translate> page, query</translate> )
<translate> Returns a [[<tvar name=1>#URI object</tvar>|URI object]] for the [[<tvar name=2>Special:MyLanguage/Help:Magic words#URL data</tvar>|local URL]] for a page, with optional query string/table. </translate>
mw.uri.new
mw.uri.new( <translate> string</translate> )
<translate> Constructs a new [[<tvar name=anchor>#URI object</tvar>|URI object]] for the passed string or table. See the description of URI objects for the possible fields for the table. </translate>
mw.uri.validate
mw.uri.validate( <translate> table</translate> )
<translate> 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 <tvar name=1>mw.uri.parseQueryString</tvar>
- 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
<tvar name=1>tostring()</tvar> will give the URI string.
Methods of the URI object are: </translate>
mw.uri:parse
uri:parse( <translate> string</translate> )
<translate> 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. </translate>
mw.uri:clone
uri:clone()
<translate> Makes a copy of the URI object. </translate>
mw.uri:extend
uri:extend( <translate> parameters</translate> )
<translate> 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 [[<tvar name=anchor>#String library</tvar>|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. </translate>
mw.ustring.maxPatternLength
<translate> The maximum allowed length of a pattern, in bytes. </translate>
mw.ustring.maxStringLength
<translate> The maximum allowed length of a string, in bytes. </translate>
mw.ustring.byte
mw.ustring.byte( s, i, j )
<translate> Returns individual bytes; identical to <tvar name=1>string.byte()</tvar>. </translate>
mw.ustring.byteoffset
mw.ustring.byteoffset( s, l, i )
<translate>
Returns the byte offset of a character in the string. The default for both <tvar name=1>l</tvar> and <tvar name=2>i</tvar> is 1. <tvar name=2>i</tvar> may be negative, in which case it counts from the end of the string.
The character at <tvar name=1>l == 1</tvar> is the first character starting at or after byte <tvar name=2>i</tvar>; the character at <tvar name=3>l == 0</tvar> is the first character starting at or before byte <tvar name=2>i</tvar>. Note this may be the same character. Greater or lesser values of <tvar name=4>l</tvar> are calculated relative to these.
</translate>
mw.ustring.char
mw.ustring.char( ... )
<translate> Much like <tvar name=1>string.char()</tvar>, except that the integers are Unicode codepoints rather than byte values. </translate>
local value = mw.ustring.char( 0x41f, 0x440, 0x438, 0x432, 0x435, 0x442, 0x21 ) -- <translate nowrap><!--T:2398--> value is now '<tvar name=1>Привет!</tvar>'</translate>
mw.ustring.codepoint
mw.ustring.codepoint( s, i, j )
<translate> Much like <tvar name=1>string.byte()</tvar>, except that the return values are codepoints and the offsets are characters rather than bytes. </translate>
mw.ustring.find
mw.ustring.find( s, pattern, init, plain )
<translate>
Much like <tvar name=3>string.find()</tvar>, except that the pattern is extended as described in [[<tvar name=anchor2>#Ustring patterns</tvar>|Ustring patterns]] and the <tvar name=2>init</tvar> offset is in characters rather than bytes.
</translate>
mw.ustring.format
mw.ustring.format( <translate> format</translate>, ... )
<translate> Identical to <tvar name=1>string.format()</tvar>. Widths and precisions for strings are expressed in bytes, not codepoints. </translate>
mw.ustring.gcodepoint
mw.ustring.gcodepoint( s, i, j )
<translate>
Returns three values for iterating over the codepoints in the string. <tvar name=1>i</tvar> defaults to 1, and <tvar name=2>j</tvar> to -1. This is intended for use in the [[<tvar name=anchor>#iterators</tvar>|iterator form of <tvar name=3>for</tvar>]]:
</translate>
for codepoint in mw.ustring.gcodepoint( s ) do
-- <translate nowrap><!--T:2169--> block</translate>
end
mw.ustring.gmatch
mw.ustring.gmatch( s, pattern )
<translate> Much like <tvar name=1>string.gmatch()</tvar>, except that the pattern is extended as described in [[<tvar name=anchor2>#Ustring patterns</tvar>|Ustring patterns]]. </translate>
Template:Red - <translate> When used with a pattern which can match the empty string, the function will get stuck in an infinite loop. For example, the following loop never terminates:</translate>
for capture in mw.ustring.gmatch( "foo bar", ".*" ) do
-- block
end
mw.ustring.gsub
mw.ustring.gsub( s, pattern, repl, n )
<translate> Much like <tvar name=1>string.gsub()</tvar>, except that the pattern is extended as described in [[<tvar name=anchor2>#Ustring patterns</tvar>|Ustring patterns]].
Template:Red: When <tvar name=1>repl</tvar> is a table, it is possible to use numbers as keys instead of strings (e.g. to replace instances of <tvar name=2>Template:Code</tvar> in a string, the value at key <tvar name=3>Template:Code</tvar> or <tvar name=4>Template:Code</tvar> would be used); as such, the output is not predictable if they have different (non-nil) values.</translate>
<translate> This is not an issue for <tvar name=2>string.gsub()</tvar>, which ignores any numbers as keys.</translate>
mw.ustring.isutf8
mw.ustring.isutf8( <translate> string</translate> )
<translate> Returns <tvar name=1>Template:Luai</tvar> if the string is valid UTF-8, <tvar name=2>Template:Luai</tvar> if not. </translate>
mw.ustring.len
mw.ustring.len( <translate> string</translate> )
<translate> Returns the length of the string in codepoints, or nil if the string is not valid UTF-8.
See <tvar name=1>string.len()</tvar> for a similar function that uses byte length rather than codepoints. </translate>
mw.ustring.lower
mw.ustring.lower( <translate> string</translate> )
<translate> Much like <tvar name=1>string.lower()</tvar>, except that all characters with lowercase to uppercase definitions in Unicode are converted.
If the [[<tvar name=anchor1>#Language library</tvar>|Language library]] is also loaded, this will instead call <tvar name=1>lc()</tvar> on the default language object. </translate>
mw.ustring.match
mw.ustring.match( s, pattern, init )
<translate>
Much like <tvar name=1>string.match()</tvar>, except that the pattern is extended as described in [[<tvar name=anchor2>#Ustring patterns</tvar>|Ustring patterns]] and the init offset is in characters rather than bytes.
</translate>
mw.ustring.rep
mw.ustring.rep( <translate> string, n</translate> )
<translate> Identical to <tvar name=1>string.rep()</tvar>. </translate>
mw.ustring.sub
mw.ustring.sub( s, i, j )
<translate> Much like <tvar name=1>string.sub()</tvar>, except that the offsets are characters rather than bytes. </translate>
mw.ustring.toNFC
mw.ustring.toNFC( <translate> string</translate> )
<translate> Converts the string to Normalization Form C (also known as Normalization Form Canonical Composition). Returns nil if the string is not valid UTF-8. </translate>
mw.ustring.toNFD
mw.ustring.toNFD( s )
<translate> Converts the string to Normalization Form D (also known as Normalization Form Canonical Decomposition). Returns nil if the string is not valid UTF-8. </translate>
mw.ustring.toNFKC
mw.ustring.toNFKC( s )
<translate> Converts the string to Normalization Form KC (also known as Normalization Form Compatibility Composition). Returns nil if the string is not valid UTF-8. </translate>
mw.ustring.toNFKD
mw.ustring.toNFKD( s )
<translate> Converts the string to Normalization Form KD (also known as Normalization Form Compatibility Decomposition). Returns nil if the string is not valid UTF-8. </translate>
mw.ustring.upper
mw.ustring.upper( s )
<translate> Much like <tvar name=1>string.upper()</tvar>, except that all characters with uppercase to lowercase definitions in Unicode are converted.
If the [[<tvar name=anchor1>#Language library</tvar>|Language library]] is also loaded, this will instead call <tvar name=1>uc()</tvar> on the default language object.
Ustring patterns
Patterns in the ustring functions use the same syntax as the [[<tvar name=anchor>#Patterns</tvar>|String library patterns]]. The major difference is that the character classes are redefined in terms of Unicode character properties:
%a: represents all characters with General Category "Letter".</translate>
<translate>
%c: represents all characters with General Category "Control".</translate>
<translate>
%d: represents all characters with General Category "Number, decimal digit".</translate>
<translate>
%l: represents all characters with General Category "Lowercase Letter".</translate>
<translate>
%p: represents all characters with General Category "Punctuation".</translate>
<translate>
%s: represents all characters with General Category "Separator", plus tab, linefeed, carriage return, vertical tab, and form feed.</translate>
<translate>
%u: represents all characters with General Category "Uppercase Letter".</translate>
<translate>
%w: represents all characters with General Category "Letter" or "Decimal Number".</translate>
<translate>
%x: adds fullwidth character versions of the hex digits.
Like in [[<tvar name=anchor1>#Patterns</tvar>|String library patterns]], <tvar name=anchor2>%A, %C, %D, %L, %P, %S, %U, %WTemplate:IntTemplate:Int%X</tvar> 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 <tvar name=1>[0-9]</tvar>, patterns such as <tvar name=2>%b«»</tvar>, and quantifiers applied to multibyte characters will work correctly. Empty captures will capture the position in code points rather than bytes.
Template:Red: Unlike [[<tvar name=anchor1>#Patterns</tvar>|String library patterns]], Ustring library patterns have a maximum length of 10,000 bytes. If the pattern exceeds this length, then the Ustring function will throw an error. Because the String library has its own maximum of 32 captures (unlike the Ustring library), it is therefore impossible to use a pattern which exceeds both limits, as it will be incompatible with both libraries.
Template:Red: 9 ASCII characters, <tvar name=1>$</tvar>, <tvar name=2>+</tvar>, <tvar name=3><</tvar>, <tvar name=4>=</tvar>, <tvar name=5>></tvar>, <tvar name=6>^</tvar>, <tvar name=7>`</tvar>, <tvar name=8>|</tvar>, <tvar name=9>~</tvar>, can be matched by <tvar name=10>%p</tvar> in the string library but not in the ustring library, as Unicode classifies them as Symbols rather than Punctuation.
Loadable libraries
These libraries are not included by default, but if needed may be loaded using <tvar name=require_function>require()</tvar>.
bit32
This emulation of the Lua 5.2 <tvar name=1>bit32</tvar> library may be loaded using:
</translate>
bit32 = require( 'bit32' )
<translate> The bit32 library provides bitwise operations on unsigned 32-bit integers. Input numbers are truncated to integers (in an unspecified manner) and reduced modulo <tvar name=1>232</tvar> so the value is in the range 0 to <tvar name=2>232−1</tvar>; return values are also in this range.
When bits are numbered (as in <tvar name=1>bit32.extract()</tvar>), 0 is the least-significant bit (the one with value <tvar name=2>20</tvar>) and 31 is the most-significant (the one with value <tvar name=3>231</tvar>). </translate>
bit32.band
bit32.band( ... )
<translate> 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. </translate>
bit32.bnot
bit32.bnot( x )
<translate>
Returns the bitwise complement of <tvar name=1>x</tvar>.
</translate>
bit32.bor
bit32.bor( ... )
<translate> 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. </translate>
bit32.btest
bit32.btest( ... )
<translate>
Equivalent to <tvar name=1>bit32.band( ... ) ~= 0</tvar>
</translate>
bit32.bxor
bit32.bxor( ... )
<translate> 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. </translate>
bit32.extract
bit32.extract( n, <translate> field, width</translate> )
<translate>
Extracts width bits from <tvar name=1>n</tvar>, starting with bit field. Accessing bits outside of the range 0 to 31 is an error.
If not specified, the default for width is 1.
</translate>
bit32.replace
bit32.replace( n, v, <translate> field, width</translate> )
<translate>
Replaces width bits in <tvar name=1>n</tvar>, starting with bit field, with the low width bits from <tvar name=2>v</tvar>. Accessing bits outside of the range 0 to 31 is an error.
If not specified, the default for width is 1.
</translate>
bit32.lshift
bit32.lshift( n, disp )
<translate>
Returns the number <tvar name=1>n</tvar> shifted <tvar name=2>disp</tvar> bits to the left. This is a logical shift: inserted bits are <tvar name=3>0</tvar>. This is generally equivalent to multiplying by <tvar name=4>2disp</tvar>.
Note that a displacement over <tvar name=1>31</tvar> will result in <tvar name=2>0</tvar>. </translate>
bit32.rshift
bit32.rshift( n, disp )
<translate>
Returns the number <tvar name=1>n</tvar> shifted <tvar name=2>disp</tvar> bits to the right. This is a logical shift: inserted bits are <tvar name=3>0</tvar>. This is generally equivalent to dividing by <tvar name=4>2disp</tvar>.
Note that a displacement over <tvar name=1>31</tvar> will result in <tvar name=2>0</tvar>. </translate>
bit32.arshift
bit32.arshift( n, disp )
<translate>
Returns the number <tvar name=1>n</tvar> shifted <tvar name=2>disp</tvar> bits to the right. This is an arithmetic shift: if <tvar name=2>disp</tvar> is positive, the inserted bits will be the same as bit <tvar name=3>31</tvar> in the original number.
Note that a displacement over <tvar name=1>31</tvar> will result in <tvar name=2>0</tvar> or <tvar name=3>4294967295</tvar>. </translate>
bit32.lrotate
bit32.lrotate( n, disp )
<translate>
Returns the number <tvar name=2>n</tvar> rotated <tvar name=1>disp</tvar> bits to the left.
Note that rotations are equivalent modulo <tvar name=1>32</tvar>: a rotation of <tvar name=1>32</tvar> is the same as a rotation of <tvar name=2>0, 33</tvar> is the same as <tvar name=3>1</tvar>, and so on. </translate>
bit32.rrotate
bit32.rrotate( n, disp )
<translate>
Returns the number <tvar name=2>n</tvar> rotated <tvar name=1>disp</tvar> bits to the right.
Note that rotations are equivalent modulo <tvar name=1>32</tvar>: a rotation of <tvar name=1>32</tvar> is the same as a rotation of <tvar name=2>0, 33</tvar> is the same as <tvar name=3>1</tvar>, and so on.
libraryUtil
This library contains methods useful when implementing Scribunto libraries. It may be loaded using: </translate>
libraryUtil = require( 'libraryUtil' )
libraryUtil.checkType
libraryUtil.checkType( <translate> name</translate>, argIdx, arg, expectType, nilOk )
<translate>
Raises an error if <tvar name=1>type( arg )</tvar> does not match <tvar name=2>expectType</tvar>. In addition, no error will be raised if <tvar name=4>arg</tvar> is nil and <tvar name=3>nilOk</tvar> is true.
name is the name of the calling function, and <tvar name=1>argIdx</tvar> is the position of the argument in the argument list. These are used in formatting the error message.
</translate>
libraryUtil.checkTypeMulti
libraryUtil.checkTypeMulti( <translate> name</translate>, argIdx, arg, expectTypes )
<translate>
Raises an error if <tvar name=1>type( arg )</tvar> does not match any of the strings in the array <tvar name=2>expectTypes</tvar>.
This is for arguments that have more than one valid type. </translate>
libraryUtil.checkTypeForIndex
libraryUtil.checkTypeForIndex( <translate> index, value</translate>, expectType )
<translate>
Raises an error if <tvar name=1>type( value )</tvar> does not match <tvar name=2>expectType</tvar>.
This is intended for use in implementing a <tvar name=1>__newindex</tvar> [[<tvar name=anchor>#Metatables</tvar>|metamethod]].
</translate>
libraryUtil.checkTypeForNamedArg
libraryUtil.checkTypeForNamedArg( <translate> name</translate>, argName, arg, expectType, nilOk )
<translate>
Raises an error if <tvar name=1>type( arg )</tvar> does not match <tvar name=2>expectType</tvar>. In addition, no error will be raised if <tvar name=3>arg</tvar> is nil and <tvar name=4>nilOk</tvar> is true.
This is intended to be used as an equivalent to <tvar name=1>libraryUtil.checkType()</tvar> in methods called using Lua's "named argument" syntax, <tvar name=2>func{ name = value }</tvar>.
</translate>
libraryUtil.makeCheckSelfFunction
libraryUtil.makeCheckSelfFunction( libraryName, varName, selfObj, selfObjDesc )
<translate>
This is intended for use in implementing "methods" on object tables that are intended to be called with the <tvar name=1>obj:method()</tvar> syntax. It returns a function that should be called at the top of these methods with the <tvar name=2>self</tvar> argument and the method name, which will raise an error if that <tvar name=3>self</tvar> object is not <tvar name=4>selfObj</tvar>.
This function will generally be used in a library's constructor function, something like this: </translate>
function myLibrary.new()
local obj = {}
local checkSelf = libraryUtil.makeCheckSelfFunction( 'myLibrary', 'obj', obj, 'myLibrary object' )
function obj:method()
checkSelf( self, 'method' )
end
function obj:method2()
checkSelf( self, 'method2' )
end
return obj
end
luabit
<translate> The [<tvar name=url>http://luaforge.net/projects/bit/</tvar> luabit] library modules "bit" and "hex" may be loaded using: </translate>
bit = require( 'luabit.bit' )
hex = require( 'luabit.hex' )
<translate>
Note that the [[<tvar name=anchor1>#bit32</tvar>|bit32 library]] contains the same operations as <tvar name=1>"luabit.bit"</tvar>, and the operations in <tvar name=2>"luabit.hex"</tvar> may be performed using <tvar name=3>string.format()</tvar> and <tvar name=tonumber_function>tonumber()</tvar>.
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 [[<tvar name=anchor>#Ustring library</tvar>|Ustring library]]. </translate>
strict
<translate> The <tvar name=1>strict</tvar> library is not a normal library; it causes an error to be raised whenever a new variable is used that is not explicitly scoped as a local variable (e.g., global variable assignment references). This functionality is typically enabled by loading at the top of a module using: </translate>
require( 'strict' )
<translate>
On many Wikimedia wikis this was formerly implemented in <tvar name=1>Module:No globals</tvar>, which was replaced via <tvar name=2>phab:T209310</tvar>. It is in part derived from <tvar name=3>strict.lua</tvar>.
</translate>
ustring
<translate> The pure-Lua backend to the [[<tvar name=anchor>#Ustring library</tvar>|Ustring library]] may be loaded using: </translate>
ustring = require( 'ustring' )
<translate>
In all cases the Ustring library (<tvar name=1>mw.ustring</tvar>) 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 <tvar name=1>mw</tvar>, usually in the table <tvar name=2>mw.ext</tvar>, however, they are only present when certain extensions are installed (in addition to the Scribunto extension itself).
Such extensions use Scribunto provided hooks:
- <tvar name=1>ScribuntoExternalLibraries</tvar>
- <tvar name=2>ScribuntoExternalLibraryPaths</tvar>
[[<tvar name=1>#Writing Scribunto libraries</tvar>|Writing Scribunto libraries]] provides information on how such libraries can be developed to provide Lua interfaces for MediaWiki extensions. </translate>
mw.wikibase
<translate> <tvar name=1>Template:Ll</tvar> provides access to localizable structured data, most notably [[<tvar name=link>d:Special:MyLanguage/Wikidata:Main Page</tvar>|Wikidata]].</translate> <translate> See <tvar name=md>docs_topics_lua.html</tvar> and <tvar name=lua>Template:Ll</tvar>.</translate>
mw.wikibase.lexeme
<translate> <tvar name=extension>Template:Ll</tvar> provides access to Wikibase Lexeme entities. This is supported by [[<tvar name=link>d:Special:MyLanguage/Wikidata:Lexicographical data</tvar>|Wikidata:Lexicographical data]].</translate> <translate> See <tvar name=md>md_docs_2topics_2lua.html</tvar> and <tvar name=lua>Template:Ll</tvar>.</translate>
mw.wikibase.mediainfo
<translate> <tvar name=extension>Template:Ll</tvar> provides access to Wikibase MediaInfo entities.</translate> <translate> See <tvar name=1>Template:Ll</tvar>.</translate> <translate> This is supported by [[<tvar name=link>c:Special:MyLanguage/Commons:Structured data</tvar>|Structured Data on Commons]]. See [[<tvar name=link2>c:Special:MyLanguage/Commons:Structured data/Lua</tvar>|Structured data/Lua]].</translate>
mw.bcmath
<translate> <tvar name=ext>Template:Ll</tvar> provides arbitrary-precision arithmetic to Lua modules. See <tvar name=extname>BCmath</tvar> documentation via "<tvar name=ldoc>LDoc</tvar>" link at [[<tvar name=extlink>Special:MyLanguage/Extension:BCmath</tvar>#Usage|<tvar name=extusage>BCmath</tvar> § Usage]].</translate>
mw.smw
<translate> <tvar name=ext>Template:Ll</tvar> provides native <tvar name=scribunto>Scribunto</tvar> support for the <tvar name=extsmw>Template:Ll</tvar> extension.</translate>
mw.ext.data
<translate> <tvar name=ext>Template:Ll</tvar> provides access to localizable tabular and map data.</translate> <translate> See <tvar name=exttab>Template:Ll</tvar>.</translate> <translate> <tvar name=tab>Template:Ll</tvar> and <tvar name=map>GeoJSON Template:Ll</tvar> is supported in the "<tvar name=data>Data:</tvar>" namespace at <tvar name=commons>Commons</tvar>.</translate>
mw.ext.data.get( pagename )
mw.ext.cargo
<translate> <tvar name=1>Template:Ll</tvar> provides a means to query its data store from Lua.</translate> <translate> See {{<tvar name=1>ll|Extension:Cargo/Other features#Lua support</tvar>|Extension:Cargo/Other features#Lua support}}.</translate>
mw.ext.cattools
<translate> <tvar name=1>Template:Ll</tvar> provides a means to check from Lua if a certain page belongs to a category.</translate> <translate> Is is experimental and not enabled on public Wikimedia wikis. But the "categories" [[<tvar name=1>#Title_objects</tvar>|field of the title object]] does the same work and is enabled.</translate>
mw.ext.FlaggedRevs
<translate> <tvar name=1>Template:Ll</tvar> provides a means to access the stability settings of a page from Lua.</translate>
mw.ext.TitleBlacklist
<translate> <tvar name=1>Template:Ll</tvar> provides a means to test and obtain information about blacklisted page naming entries from Lua.</translate>
mw.ext.translate.messageBundle
<translate> [EXPERIMENTAL] Part of the <tvar name=1>Template:Ll</tvar> extension. Provides a means to query translations present inside <tvar name=2>Template:Ll</tvar>. Read <tvar name=3>Template:Ll</tvar> for more information.</translate>
mw.ext.ParserFunctions
<translate> <tvar name=ext>Template:Ll</tvar> provides a means from Lua to evaluate expressions in the same way as its PHP-based parser function <tvar name=see>Template:Ll</tvar>.</translate>
mw.ext.proofreadPage
<translate> <tvar name=1>Template:Ll</tvar> provides access to Index and Page namespaces.</translate> <translate> See <tvar name=1>Template:Ll</tvar>.</translate> <translate> This is supported by <tvar name=1>Wikisource:ProofreadPage</tvar>.</translate> <translate> See <tvar name=1>Template:Ll</tvar>.</translate>
mw.ext.articlePlaceholder
<translate> <tvar name=1>Template:Ll</tvar> provides a means to override default Wikibase renderings from Lua.</translate> <translate> See <tvar name=1>Template:Ll</tvar>.</translate>
mw.ext.externalData
<translate> <tvar name=1>Template:Ll</tvar> provides a means to get structured data from Internet from Lua.</translate> <translate> See <tvar name=1>Template:Ll</tvar>.</translate>
mw.ext.UnlinkedWikibase
<translate> See <tvar name=1>Template:Ll</tvar></translate>
mw.ext.UnlinkedWikibase.getEntity( id )mw.ext.UnlinkedWikibase.query( sparql )
mw.ext.seo
<translate> <tvar name=1>WikiSEO</tvar> provides a means to set SEO Data for the current page. See [[<tvar name=2>Extension:WikiSEO#Usage in lua modules</tvar>|WikiSEO#Usage in lua modules]].</translate>
mw.slots
<translate> <tvar name=1>Template:Ll</tvar> provides a number of Lua functions for working with [[<tvar name=2>Special:MyLanguage/Multi-Content Revisions</tvar>|MCR]] slots:</translate>
mw.slots.slotContent(slotName, pageName)mw.slots.slotTemplates(slotName, pageName)(deprecated)mw.slots.slotContentModel(slotName, pageName)mw.slots.slotData(slotName, pageName)
<translate>
Differences from standard Lua
Changed functions
The following functions have been modified: </translate>
- setfenv()
- getfenv()
- <translate> May not be available, depending on the configuration. If available, attempts to access parent environments will fail.</translate>
- getmetatable()
- <translate> Works on tables only to prevent unauthorized access to parent environments.</translate>
- tostring()
- <translate> Pointer addresses of tables and functions are not provided. This is to make memory corruption vulnerabilities more difficult to exploit.</translate>
- pairs()
- ipairs()
- <translate> Support for the <tvar name=1>__pairs</tvar> and <tvar name=2>__ipairs</tvar> metamethods (added in Lua 5.2) has been added.</translate>
- pcall()
- xpcall()
- <translate> Certain internal errors cannot be intercepted.</translate>
- require()
- <translate> 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.</translate>
<translate>
Removed functions and packages
The following packages are mostly removed. Only those functions listed are available: </translate>
- package.*
- <translate> Filesystem and C library access has been removed.</translate> <translate> Available functions and tables are:</translate>
- package.loaded
- package.preload
- package.loaders
- <translate> Loaders which access the local filesystem or load C libraries are not present.</translate> <translate> A loader for Module-namespace pages is added.</translate>
- package.seeall()
- os.*
- <translate> There are some insecure functions in here, such as <tvar name=1>os.execute()</tvar>, which can't be allowed.</translate> <translate> Available functions are:</translate>
- debug.*
- <translate> Most of the functions are insecure.</translate> <translate> Available functions are:</translate>
<translate> The following functions and packages are not available: </translate>
- collectgarbage()
- module()
- coroutine.*
- <translate> No application is known for us, so it has not been reviewed for security.</translate>
- dofile()
- loadfile()
- io.*, file.*
- <translate> Allows local filesystem access, which is insecure.</translate>
- load()
- loadstring()
- <translate> These were omitted to allow for static analysis of the Lua source code.</translate> <translate> Also, allowing these would allow Lua code to be added directly to article and template pages, which was not desired for usability reasons.</translate>
- print()
- <translate> This was [[<tvar name=1>mailarchive:wikitech-l/2012-April/059995.html</tvar>|discussed on wikitech-l]] and it was decided that it should be omitted in favour of return values, to improve code quality.</translate> <translate> If necessary, <tvar name=1>mw.log()</tvar> may be used to output information to the debug console.</translate>
- string.dump()
- <translate> May expose private data from parent environments.</translate>
<translate>
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.</translate> <translate> Attempting to do so will cause undefined behavior.</translate> <translate> This includes (but is not limited to) returning such data structures from the module called by <tvar name=1>
{{#invoke:}}</tvar> and passing such data structures as parameters to Scribunto library functions that are implemented as callbacks into PHP.</translate>
<translate> Such data structures may be used freely within Lua, including as the return values of modules loaded with <tvar name=1>mw.loadData()</tvar>.</translate>
<translate>
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 <tvar name=1>Scribunto_LuaLibraryBase</tvar>. See the documentation for that class for implementation details. In the Scribunto extension, this file should be placed in <tvar name=2>engines/LuaCommon/NameLibrary.php</tvar>, and a mapping added to <tvar name=3>Scribunto_LuaEngine::$libraryClasses</tvar>. Other extensions should use the <tvar name=4>ScribuntoExternalLibraries</tvar> hook. In either case, the key should match the Lua module name (<tvar name=5>"mw.name"</tvar> for libraries in Scribunto, or <tvar name=6>"mw.ext.name"</tvar> 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 <tvar name=1>engines/LuaCommon/lualib/mw.name.lua</tvar>. This file should generally include boilerplate something like this:
</translate>
local object = {}
local php
function object.setupInterface( options )
-- <translate nowrap><!--T:2300--> Remove setup function</translate>
object.setupInterface = nil
-- <translate nowrap><!--T:2301--> Copy the PHP callbacks to a local variable, and remove the global</translate>
php = mw_interface
mw_interface = nil
-- <translate nowrap><!--T:2302--> Do any other setup here</translate>
-- <translate nowrap><!--T:2303--> Install into the mw global</translate>
mw = mw or {}
mw.ext = mw.ext or {}
mw.ext.NAME = object
-- <translate nowrap><!--T:2304--> Indicate that we're loaded</translate>
package.loaded['mw.ext.NAME'] = object
end
return object
<translate>
The module in <tvar name=1>engines/LuaCommon/lualib/libraryUtil.lua</tvar> (load this with <tvar name=2>local util = require 'libraryUtil'</tvar>) 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 <tvar name=1>#invoke</tvar>'s. Care must be taken to ensure that modules can't abuse this to transfer information between #invoke's.
Test cases
</translate>
<translate> The Scribunto extension includes a base class for test cases, <tvar name=1>Scribunto_LuaEngineTestBase</tvar>, which will run the tests against both the <tvar name=lsb>Template:Ll</tvar> and <tvar name=lsa>Template:Ll</tvar> engines.</translate>
<translate> The library's test case should extend this class, and should not override static function <tvar name=1>suite()</tvar>.</translate>
<translate> In the <tvar name=ext>Scribunto</tvar> extension, the test case should be in <tvar name=lt>tests/engines/LuaCommon/NameLibraryTest.php</tvar> and added to the array in <tvar name=1>Template:Phpi</tvar> (in <tvar name=2>common/Hooks.php</tvar>); extensions should add the test case in their own <tvar name=3>Template:Ll</tvar> hook function, probably conditional on whether <tvar name=4>$wgAutoloadClasses['Scribunto_LuaEngineTestBase']</tvar> is set.</translate>
<translate> Most of the time, all that is needed to make the test case is this: </translate>
class ClassNameTest extends Scribunto_LuaEngineTestBase {
protected static $moduleName = 'ClassNameTest';
function getTestModules() {
return parent::getTestModules() + array(
'ClassNameTest' => __DIR__ . '/ClassNameTests.lua';
);
}
}
<translate>
This will load the file <tvar name=1>ClassNameTests.lua</tvar> as if it were the page <tvar name=2>"Module:ClassNameTests"</tvar>, expecting it to return an object with the following properties:
</translate>
- count: <translate> Integer, number of tests</translate>
- provide( n ): <translate> Function that returns three values: <tvar name=1>
n</tvar>, the name of test <tvar name=1>n</tvar>, and a string that is the expected output for test <tvar name=1>n</tvar>.</translate> - run( n ): <translate> Function that runs test <tvar name=1>
n</tvar> and returns one string.</translate>
<translate>
If <tvar name=1>getTestModules()</tvar> is declared as shown, <tvar name=2>"Module:TestFramework"</tvar> is available which provides many useful helper methods. If this is used, <tvar name=3>ClassNameTests.lua</tvar> would look something like this:
</translate>
local testframework = require 'Module:TestFramework'
return testframework.getTestProvider( {
-- <translate> Tests go here</translate>
} )
<translate> Each test is itself a table, with the following properties:</translate>
- name: <translate> The name of the test.</translate>
- func: <translate> The function to execute.</translate>
- args: <translate> Optional table of arguments to pass to the function.</translate>
- expect: <translate> Results to expect.</translate>
- type: <translate> Optional "type" of the test, default is "Normal".</translate>
<translate> The type controls the format of <tvar name=expect>expect</tvar> and how <tvar name=func>func</tvar> is called. Included types are:</translate>
- Normal: <translate> <tvar name=expect>
expect</tvar> is a table of return values, or a string if the test should raise an error.</translate> <translate> <tvar name=func>func</tvar> is simply called.</translate> - Iterator: <translate> <tvar name=expect>
expect</tvar> is a table of tables of return values.</translate> <translate> <tvar name=func>func</tvar> is called as with an [[<tvar name=1>#iterators</tvar>|iterated for loop]], and each iteration's return values are accumulated.</translate> - ToString: <translate> Like "Normal", except each return value is passed through <tvar name=1>
tostring()</tvar>.</translate>
<translate>
Test cases in another extension
There are (at least) two ways to run PHPUnit tests:
- Run PHPUnit against core, allowing the <tvar name=1>tests/phpunit/suites/ExtensionsTestSuite.php</tvar> to find the extension's tests using the <tvar name=2>Template:Ll</tvar> hook.</translate> <translate> If your extension's test class names all contain a unique component (e.g. the extension's name), the <tvar name=1>
--filter</tvar> option may be used to run only your extension's tests.</translate>
<translate>
- Run PHPUnit against the extension directory, where it will pick up any file ending in "<tvar name=1>Test.php</tvar>".
Either of these will work fine if Scribunto is loaded in <tvar name=2>LocalSettings.php</tvar>. And it is easy for method <tvar name=3>#1</tvar> to work if Scribunto is not loaded, as the UnitTestsList hook can easily be written to avoid returning the Scribunto test when <tvar name=1>Template:Phpi</tvar> is not set.
But <tvar name=1>Jenkins</tvar> uses method <tvar name=2>#2</tvar>. For Jenkins to properly run the tests, you will need to add Scribunto as a dependency for your extension. See <tvar name=gerrit>Template:Gerrit</tvar> for an example of how this is done.
If for some reason you need the tests to be able to run using method <tvar name=1>#2</tvar> without Scribunto loaded, one workaround is to add this check to the top of your unit test file: </translate>
if ( !isset( $GLOBALS['wgAutoloadClasses']['Scribunto_LuaEngineTestBase'] ) ) {
return;
}
<translate>
Documentation
Modules included in Scribunto should include documentation in the [[<tvar name=anchor>#Scribunto libraries</tvar>|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.
See also
License
This manual is derived from the [<tvar name=url1>https://www.lua.org/manual/5.1/index.html</tvar> Lua 5.1 reference manual], which is available under the [<tvar name=url2>https://www.lua.org/license.html</tvar> MIT license]. </translate>
[[Category:Lua{{#translation:}}]]