Extension:Scribunto/Lua reference manual: Difference between revisions

Content deleted Content added
No edit summary
Marked this version for translation
Line 1:
<translate>
<!--T:1-->
{{languages|Extension:Scribunto/Lua reference manual}}
{{TNT|Shortcut|Lua manual|LUAREF}}
 
<!--T:2-->
This manual documents [[Lua]] as it is used in MediaWiki with the [[Extension:Scribunto|Scribunto]] extension. Some parts are derived from the [http://www.lua.org/manual/5.1/index.html Lua 5.1 reference manual], which is available under the [[#License|MIT license]].
 
<!--T:3-->
{{mbox
| type = notice
Line 11 ⟶ 14:
<div style="float:right;margin-left:1em;"> __TOC__ </div>
 
== Introduction == <!--T:4-->
=== Getting started ===
 
<!--T:5-->
On a MediaWiki wiki with Scribunto enabled, [[Help:Starting a new page|create a page]] with a title starting with "Module:", for example "Module:Bananas". Into this new page, copy the following text:
 
<!--T:6-->
<syntaxhighlight lang="lua">
local p = {}
 
<!--T:7-->
function p.hello( frame )
return "Hello, world!"
end
 
<!--T:8-->
return p
</syntaxhighlight>
 
<!--T:9-->
Save that, then on another (non-module) page, write:
 
<!--T:10-->
<pre>
{{#invoke:Bananas|hello}}
</pre>
 
<!--T:11-->
Except that you should replace "Bananas" with whatever you called your module. This will call the "hello" function exported from that module. The <nowiki>{{#invoke:Bananas|hello}}</nowiki> will be replaced with the text that the function returned, in this case, "Hello, world!"
 
<!--T:12-->
It's generally a good idea to invoke Lua code from the context of a template. 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. It also avoids the introduction of additional complex syntax into the content namespace of a wiki.
 
=== Module structure === <!--T:13-->
 
<!--T:14-->
The module itself must return a table containing the functions that may be called by <code><nowiki>{{#invoke:}}</nowiki></code>. 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.
 
<!--T:15-->
Any functions that are not added to this table, whether local or global, will not be accessible by <code><nowiki>{{#invoke:}}</nowiki></code>, but globals might be accessible from other modules loaded using <code>[[#require|require()]]</code>. It is generally good style for the module to declare all functions and variables local.
 
=== Accessing parameters from wikitext === <!--T:16-->
 
<!--T:17-->
Functions called by <code><nowiki>{{#invoke:}}</nowiki></code> will be passed a single parameter, that being a [[#Frame object|frame object]]. To access the parameters passed to the <code><nowiki>{{#invoke:}}</nowiki></code>, code will typically use the [[#frame.args|<code>args</code> table of that frame object]]. It's also possible to access the parameters passed to the template containing the <code><nowiki>{{#invoke:}}</nowiki></code> by using [[#frame:getParent|</code>frame:getParent()</code>]] and accessing that frame's <code>args</code>.
 
<!--T:18-->
This frame object is also used to access context-specific features of the wikitext parser, such as [[#frame:callParserFunction|calling parser functions]], [[#frame:expandTemplate|expanding templates]], and [[#frame:preprocess|expanding arbitrary wikitext strings]].
 
=== Returning text === <!--T:19-->
 
<!--T:20-->
The module function should usually return a single string; whatever values are returned will be passed through [[#tostring|tostring()]] and then concatenated with no separator. This string is incorporated into the wikitext as the result of the <code><nowiki>{{#invoke:}}</nowiki></code>.
 
<!--T:21-->
At this point in the page parse, templates have already been expanded, parser functions and extension tags have already been processed, and pre-save transforms (e.g. signature tilde expansion and the [[Help:Pipe trick|pipe trick]]) have already happened. Therefore the module cannot use these features in its output text. For example, if a module returns <code><nowiki>"Hello, [[world]]! {{welcome}}"</nowiki></code>, the page will read "Hello, [[world]]! <nowiki>{{welcome}}</nowiki>".
 
<!--T:22-->
On the other hand, [[mw:Help:Substitution|subst]] is handled at an earlier stage of processing, so with <code><nowiki>{{subst:#invoke:}}</nowiki></code> 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 === <!--T:23-->
 
<!--T:24-->
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 "Module:Bananas" would be at "Module:Bananas/doc".
 
<!--T:25-->
This can be configured using the following [[:meta:Help:System message|MediaWiki-namespace messages]]:
* '''scribunto-doc-page-name''': Sets the name of the page used for documentation. The name of the module (without the Module: prefix) is passed as <code>$1</code>. If in the module namespace, the pages specified here will be interpreted as wikitext rather than Lua source and may not be used with <code><nowiki>{{#invoke:}}</nowiki></code>. The default is "Module:$1/doc", i.e. the /doc subpage of the module. Note that parser functions and other brace expansion may not be used in this message.
Line 66 ⟶ 86:
* '''scribunto-doc-page-header''': Header displayed when viewing the documentation page itself. The name of the module (with Module: prefix) being documented is passed as <code>$1</code>. The default simply displays a short explanation in italics.
 
<!--T:26-->
Note that modules cannot be directly categorized and cannot have interwiki links directly added. These could be placed on the documentation page inside <code><nowiki><includeonly>...</includeonly></nowiki></code> tags, where they will be applied to the module when the documentation page is transcluded onto the module page.
 
== Lua language == <!--T:27-->
 
=== Tokens === <!--T:28-->
 
<!--T:29-->
{{Anchor|name}}
''Names'' (also called ''identifiers'') 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.
 
<!--T:30-->
The following keywords are reserved and may not be used as names:
<div style="margin:0.3em 1.6em; column-width: 10em; -moz-column-width: 10em; -webkit-column-width: 10em">
Line 101 ⟶ 124:
Names starting with an underscore followed by uppercase letters are reserved for internal Lua global variables.
 
<!--T:31-->
Other tokens are:
<div style="margin:0.3em 1.6em; column-width: 10em; -moz-column-width: 10em; -webkit-column-width: 10em">
Line 131 ⟶ 155:
</div>
 
=== Comments === <!--T:32-->
 
<!--T:33-->
A comment starts with a <code>--</code> anywhere outside a string. If the <code>--</code> is immediately followed by [[#long brackets|an opening long bracket]], the comment continues to the corresponding closing long bracket; otherwise the comment runs to the end of the current line.
<source lang="lua">
Line 146 ⟶ 171:
</source>
 
=== Data types === <!--T:34-->
 
<!--T:35-->
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.
 
<!--T:36-->
Lua has eight basic data types, however only six are relevant to the Scribunto extension. The <code>[[#type|type()]]</code> function will return the type of a value.
 
<!--T:37-->
The <code>[[#tostring|tostring()]]</code> function will convert a value to a string. The <code>[[#tonumber|tonumber()]]</code> 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.
 
<!--T:38-->
Numbers are automatically converted to strings when used where a string is expected, e.g. when used with the concatenation operator. Strings recognized by <code>[[#tonumber|tonumber()]]</code> 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 ==== <!--T:39-->
 
<!--T:40-->
"nil" is the data type of <code>nil</code>, which exists to represent the absence of a value.
 
<!--T:41-->
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.
 
<!--T:42-->
When converted to a string, the result is "nil". When converted to boolean, nil is considered false.
 
==== boolean ==== <!--T:43-->
 
<!--T:44-->
Boolean values are <code>true</code> and <code>false</code>.
 
<!--T:45-->
When converted to a string, the result is "true" or "false".
 
<!--T:46-->
Unlike many other languages, boolean values may not be directly converted to numbers. And unlike many other languages, only false and nil are considered false for boolean conversion; the number 0 and the empty string are both considered true.
 
==== string ==== <!--T:47-->
 
<!--T:48-->
Lua strings are considered a series of 8-bit bytes; it is up to the application to interpret them in any particular encoding.
 
<!--T:49-->
String literals may be delimited by either single or double quotes (<code>'</code> or <code>"</code>); like JavaScript and unlike PHP, there is no difference between the two. The following escape sequences are recognized:
<div style="column-width:20em; -moz-column-width:20em; -webkit-column-width:20em">
Line 191 ⟶ 228:
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 '\''ddd''', where ''ddd'' is the decimal value of the byte in the range 0–255. To include Unicode characters using escape sequences, the individual bytes for the [[:en:UTF-8|UTF-8]] encoding must be specified; in general, it will be more straightforward to enter the Unicode characters directly.
 
<!--T:50-->
{{Anchor|long brackets}}
Literal strings can also be defined using ''long brackets''. 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. <code>[[</code>, <code>[=[</code>, or <code>[=====[</code>. The opening long bracket must be matched by the corresponding closing long bracket, e.g. <code>]]</code>, <code>]=]</code>, or <code>]=====]</code>. 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. Strings delimited by long brackets do not interpret escape sequences.
Line 199 ⟶ 237:
]]
 
<!--T:51-->
-- is equivalent to this quote-delimited string
bar = 'bar\\tbaz\n'
</syntaxhighlight>
 
<!--T:52-->
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 ==== <!--T:53-->
 
<!--T:54-->
Lua has only one numeric type, which is typically represented internally as a [[:en:double-precision floating-point format|double-precision floating-point value]]. In this format, integers between -9007199254740992 and 9007199254740992 may be represented exactly, while larger numbers and numbers with a fractional part may suffer from round-off error.
 
<!--T:55-->
Number constants are specified using a period (<code>.</code>) as a decimal separator and without grouping separators, e.g. <code>123456.78</code>. Numbers may also be represented using [[:en:E notation|E notation]] without spaces, e.g. <code>1.23e-10</code>, <code>123.45e20</code>, or <code>1.23E5</code>. Integers may also be specified in hexadecimal notation using a <code>0x</code> prefix, e.g. <code>0x3A</code>.
 
<!--T:56-->
Although [[:en:NaN|NaN]] and positive and negative infinities are correctly stored and handled, Lua does not provide corresponding literals. The constant <code>math.huge</code> is positive infinity, as is a division such as <code>1/0</code>, and a division such as <code>0/0</code> may be used to quickly generate a NaN.
 
<!--T:57-->
Note that all numbers are considered true when converted to boolean. This is unlike most other languages, where the number 0 is usually considered false. When converted to a string, finite numbers are represented in decimal, possibly in E notation; NaN is "nan" or "-nan"; and infinities are "inf" or "-inf".
 
==== table ==== <!--T:58-->
 
<!--T:59-->
Lua tables are associative arrays, much like PHP arrays and JavaScript objects.
 
<!--T:60-->
Tables are created using curly braces. The empty table is <code>{}</code>. 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:
* <code style="white-space:nowrap">[''[[#Expressions|expression1]]''] = ''[[#Expressions|expression2]]''</code> uses the (first) value of ''expression1'' as the key and the (first) value of ''expression2'' as the value.
Line 224 ⟶ 270:
* <code>''[[#Expressions|expression]]''</code> is roughly equivalent to <code style="white-space:nowrap">[''i''] = ''expression''</code>, where ''i'' 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.
 
<!--T:61-->
The fields in a table are accessed using bracket notation, e.g. <code>table[key]</code>. String keys that are also valid [[#name|names]] may also be accessed using dot notation, e.g. <code>table.key</code> is equivalent to <code>table['key']</code>. Calling a function that is a value in the table may use colon notation, e.g. <code style="white-space:nowrap">table:func( ... )</code>, which is equivalent to <code style="white-space:nowrap">table['func']( table, ... )</code>.
 
<!--T:62-->
{{Anchor|sequence}}
A ''sequence'' 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 sequences, and ignore non-positive-integer keys.
 
<!--T:63-->
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:
<syntaxhighlight lang="lua">
Line 234 ⟶ 283:
t = {}
 
<!--T:64-->
t["foo"] = "foo"
t.bar = "bar"
Line 245 ⟶ 295:
t[t] = "yes, a table may be a table key too. Even in itself."
 
<!--T:65-->
-- This creates a table roughly equivalent to the above
t2 = {
Line 260 ⟶ 311:
</syntaxhighlight>
 
<!--T:66-->
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.
 
<!--T:67-->
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.
 
<!--T:68-->
When converted to a string, the usual result is "table" but may be overridden using the <code>__tostring</code> [[#Metatables|metamethod]]. Even the empty table is considered true as a boolean.
 
==== function ==== <!--T:69-->
 
<!--T:70-->
Functions in Lua are first-class values: they may be created anonymously, passed as arguments, assigned to variables, and so on.
 
<!--T:71-->
Functions are created using the <code>function</code> 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 [[#Function declarations|Function declarations]] and [[#Function calls|Function calls]] below for details.
 
<!--T:72-->
Lua functions are [[:en:Closure (computer science)|closures]], meaning that they maintain a reference to the scope in which they are declared and can access and manipulate variables in that scope.
 
<!--T:73-->
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.
 
<!--T:74-->
When converted to a string, the result is "function".
 
==== Unsupported types ==== <!--T:75-->
 
<!--T:76-->
{{Anchor|userdata}}
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.
 
<!--T:77-->
{{Anchor|thread}}
The ''thread'' type represents the handles for coroutines, which are not available in Scribunto's sandbox.
 
=== Metatables === <!--T:78-->
 
<!--T:79-->
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 [[#getmetatable|getmetatable()]] function, and set with the [[#setmetatable|setmetatable()]] function.
 
<!--T:80-->
When being accessed for their meta functions, metatable fields are accessed as if with [[#rawget|rawget()]].
 
<!--T:81-->
Metatable fields that affect the table itself are:
; __index : This is used when a table access <code>t[key]</code> would return nil. If the value of this field is a table, the access will be repeated in that table, i.e. <code>__index[key]</code> (which may invoke that table's metatable's __index). If the value of this field is a function, the function will be called as <code style="white-space:nowrap">__index( t, key )</code>. The [[#rawget|rawget()]] function bypasses this metamethod.
Line 298 ⟶ 362:
; {{Anchor|weak tables}}__mode : This is used to make tables holding weak references. The value must be a string. By default, any value that is used as a key or as a value in a table will not be garbage collected. But if this metafield contains the letter 'k', keys may be garbage collected if there are no non-weak references, and if it contains 'v' values may be; in either case, both the corresponding key and value are removed from the table. Note that behavior is undefined if this field is altered after the table is used as a metatable.
 
<!--T:82-->
Other metatable fields include:
<div style="margin:0 1.6em; column-width: 10em; -moz-column-width: 10em; -webkit-column-width: 10em">
Line 322 ⟶ 387:
</div>
 
<!--T:83-->
Note: In Lua, all strings also share a single metatable, in which __index refers to the [[#String library|<code>string</code>]] table. This metatable is not accessible in Scribunto, nor is the referenced <code>string</code> table; the string table available to modules is a copy.
 
=== Variables === <!--T:84-->
 
<!--T:85-->
Variables are places that store values. There are three kinds of variables in Lua: global variables, local variables, and table fields.
 
<!--T:86-->
A [[#name|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 <code>local</code> keyword. Any variable that has not been assigned a value is considered to have a nil value.
 
<!--T:87-->
Global variables are stored in a standard Lua table called an ''environment''; this table is often available as the global variable <code>_G</code>. It is possible to set a metatable for this global variable table; the __index and __newindex 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.
 
<!--T:88-->
The environment for a function may be accessed using the [[#getfenv|getfenv()]] function and changed using the [[#setfenv|setfenv()]] function; in Scribunto, these functions are severely restricted if they are available at all.
 
<!--T:89-->
Local variables are lexically scoped; see [[#Local variable declarations|Local variable declarations]] for details.
 
=== Expressions === <!--T:90-->
 
<!--T:91-->
An ''expression'' is something that has values: literals (numbers, strings, true, false, nil), anonymous function declarations, table constructors, variable references, function calls, the [[#varargs|vararg expression]], expressions wrapped in parentheses, unary operators applied to expressions, and expressions combined with binary operators.
 
<!--T:92-->
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.
 
<!--T:93-->
{{Anchor|expression-list|exp-list}}
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 ==== <!--T:94-->
 
<!--T:95-->
Lua supports the usual arithmetic operators: addition, subtraction, multiplication, division, modulo, exponentiation, and negation.
 
<!--T:96-->
When all operands are numbers or strings for which [[#tonumber|tonumber()]] returns non-nil, the operations have their usual meaning.
 
<!--T:97-->
If either operand is a table with an appropriate [[#Metatables|metamethod]], the metamethod will be called.
 
<!--T:98-->
{| class="wikitable" style="text-align:center"
|-
Line 372 ⟶ 450:
|}
 
==== Relational operators ==== <!--T:99-->
 
<!--T:100-->
The relational operators in Lua are <code>==</code>, <code>~=</code>, <code><</code>, <code>></code>, <code><=</code>, and <code>>=</code>. The result of a relational operator is always a boolean.
 
<!--T:101-->
Equality (<code>==</code>) 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; <code style="white-space:nowrap">function() end == function() end</code> 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 __eq [[#Metatables|metamethod]].
 
<!--T:102-->
Inequality (<code>~=</code>) is the exact negation of equality.
 
<!--T:103-->
For the ordering operators, if both are numbers or both are strings, they are compared directly. Next, metamethods are checked:
* <code style="white-space:nowrap">a < b</code> uses <code>__lt</code>
Line 387 ⟶ 469:
If the necessary metamethods are not available, an error is raised.
 
==== Logical operators ==== <!--T:104-->
 
<!--T:105-->
The logical operators are <code>and</code>, <code>or</code>, and <code>not</code>. All use the standard interpretation where nil and false are considered false and anything else is considered true.
 
<!--T:106-->
For <code>and</code>, if the left operand is considered false then it is returned and the second operand is not evaluated; otherwise the second operand is returned.
 
<!--T:107-->
For <code>or</code>, if the left operand is considered true then it is returned and the second operand is not evaluated; otherwise the second operand is returned.
 
<!--T:108-->
For <code>not</code>, the result is always true or false.
 
<!--T:109-->
Note that <code>and</code> and <code>or</code> short circuit. For example, <code style="white-space:nowrap">foo() or bar()</code> will only call <code>bar()</code> if <code>foo()</code> returns false or nil as its first value.
 
==== Concatenation operator ==== <!--T:110-->
 
<!--T:111-->
The concatenation operator is two dots, used as <code style="white-space:nowrap">a .. b</code>. If both operands are numbers or strings, they are converted to strings and concatenated. Otherwise if a __concat [[#Metatables|metamethod]] is available, it is used. Otherwise, an error is raised.
 
<!--T:112-->
Note that Lua strings are immutable and Lua does not provide any sort of "string builder", so a loop that repeatedly does <code style="white-space:nowrap">a = a .. b</code> 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 [[#string.format|string.format()]] or to insert all the strings into a [[#sequence|sequence]] and use [[#table.concat|table.concat()]] at the end.
 
==== Length operator ==== <!--T:113-->
 
<!--T:114-->
The length operator is <code>#</code>, used as <code>#a</code>. If <code>a</code> is a string, it returns the length in bytes. If <code>a</code> is a [[#sequence|sequence]] table, it returns the length of the sequence.
 
<!--T:115-->
If <code>a</code> is a table that is ''not'' a sequence, the <code>#a</code> may return any value N such that a[N] is not nil and a[N+1] is nil, even if there are non-nil values at higher indexes. For example,
 
<!--T:116-->
<syntaxhighlight lang="lua">
-- This is not a sequence, because a[3] is nil and a[4] is not
a = { 1, 2, nil, 4 }
 
<!--T:117-->
-- This may output either 2 or 4.
-- And this may change even if the table is not modified.
Line 420 ⟶ 513:
</syntaxhighlight>
 
==== Operator precedence ==== <!--T:118-->
 
<!--T:119-->
Lua's [[:en:operator precedence|operator precedence]], from highest to lowest:
 
<!--T:120-->
* ^
* not # - (negation)
Line 433 ⟶ 528:
* or
 
<!--T:121-->
Within a precedence level, most binary operators are left-associative, i.e. <code style="white-space:nowrap">a + b + c</code> is interpreted as <code style="white-space:nowrap">(a + b) + c</code>. Exponentiation and concatenation are right-associative, i.e. <code style="white-space:nowrap">a ^ b ^ c</code> is interpreted as <code style="white-space:nowrap">a ^ (b ^ c)</code>.
 
==== Function calls ==== <!--T:122-->
 
<!--T:123-->
Lua function calls look like those in most other languages: a name followed by a list of arguments in parentheses:
 
<!--T:124-->
func( [[#expression-list|''expression-list'']] )
func( [[#expression-list|''expression-list'']] )
 
<!--T:125-->
As is usual with expression lists in Lua, the last expression in the list may supply multiple argument values.
 
<!--T:126-->
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 [[#Function declarations|Function declarations]] for details.
 
<!--T:127-->
Lua also allows direct calling of a function return value, i.e. <code>func()()</code>. 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.
 
<!--T:128-->
Lua has [[:en:syntactic sugar|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
 
<!--T:129-->
table:name( [[#expression-list|''expression-list'']] )
table:name( [[#expression-list|''expression-list'']] )
 
<!--T:130-->
is exactly equivalent to
 
<!--T:131-->
table.name( table, [[#expression-list|''expression-list'']] )
table.name( table, [[#expression-list|''expression-list'']] )
 
<!--T:132-->
{{Anchor|named arguments}}
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
 
<!--T:133-->
func{ arg1 = ''exp'', arg2 = ''exp'' }
func{ arg1 = ''exp'', arg2 = ''exp'' }
func"string"
 
<!--T:134-->
are equivalent to
 
<!--T:135-->
func( { arg1 = ''exp'', arg2 = ''exp'' } )
func( { arg1 = ''exp'', arg2 = ''exp'' } )
func( "string" )
 
<!--T:136-->
These may be combined; the following calls are equivalent:
 
<!--T:137-->
table:name{ arg1 = ''exp'', arg2 = ''exp'' }
table:name{ arg1 = ''exp'', arg2 = ''exp'' }
table.name( table, { arg1 = ''exp'', arg2 = ''exp'' } )
 
==== Function declarations ==== <!--T:138-->
 
<!--T:139-->
The syntax for function declaration looks like this:
 
<!--T:140-->
function ( ''var-list'' )
function ( ''var-list'' )
''block''
end
 
<!--T:141-->
All variables in ''var-list'' are local to the function, with values assigned from the expression list in the [[#Function calls|function call]]. Additional local variables may be declared inside the block.
 
<!--T:142-->
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 [[#return|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.
 
<!--T:143-->
Lua functions are [[:en:Closure (computer science)|lexical closures]]. A common idiom is to declare "private static" variables as locals in the scope where the function is declared. For example,
 
<!--T:144-->
-- This returns a function that adds a number to its argument
-- This returns a function that adds a number to its argument
function makeAdder( n )
return function( x )
Line 497 ⟶ 614:
-- prints 11
 
<!--T:145-->
{{Anchor|varargs}}
A function may be declared to accept a variable number of arguments, by specifying <code>...</code> as the final item in the ''var-list'':
 
<!--T:146-->
function ( ''var-list'', ... )
function ( ''var-list'', ... )
''[[#block|block]]''
end
 
<!--T:147-->
Within the block, the varargs expression <code>...</code> may be used, with the result being all the extra values in the function call. For example,
 
<!--T:148-->
local join = function ( separator, ... )
local join = function ( separator, ... )
-- get the extra arguments as a table
local args = { ... }
Line 517 ⟶ 638:
-- returns the string "foo, bar, baz"
 
<!--T:149-->
The [[#select|select()]] function is designed to work with the varargs expression; in particular, <code style="white-space:nowrap">select( '#', ... )</code> should be used instead of <code style="white-space:nowrap">#{ ... }</code> to count the number of values in the varargs expression.
 
 
<!--T:150-->
Lua provides [[:en:syntactic sugar|syntactic sugar]] to combine function declaration and assignment to a variable; see [[#Function declaration statements|Function declaration statements]] for details.
 
<!--T:151-->
Note that this will not work:
<pre style="background-color:#fcc">
Line 534 ⟶ 658:
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 [[#Function declaration statements|function declaration statement]] syntax.
 
=== Statements === <!--T:152-->
 
<!--T:153-->
A ''statement'' is the basic unit of execution: one assignment, control structure, function call, variable declaration, etc.
 
<!--T:154-->
{{Anchor|chunk}}
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.
 
<!--T:155-->
{{Anchor|block}}
A ''block'' is also a sequence of statements, just like a chunk. A block can be delimited to create a single statement: <code style="white-space:nowrap">do ''block'' end</code>. These may be used to limit the scope of local variables, or to add a <code>return</code> or <code>break</code> in the middle of another block.
 
==== Assignments ==== <!--T:156-->
 
<!--T:157-->
<code style="white-space:nowrap">''variable-list'' = [[#expression-list|''expression-list'']]</code>
 
<!--T:158-->
The ''variable-list'' is a comma-separated list of variables; the ''expression-list'' is a comma-separated list of one or more expressions. All expressions are evaluated before any assignments are performed, so <code style="white-space:nowrap">a, b = b, a</code> will swap the values of <var>a</var> and <var>b</var>.
 
==== Local variable declarations ==== <!--T:159-->
 
<!--T:160-->
<code style="white-space:nowrap">local ''variable-list''</code>
 
<!--T:161-->
<code style="white-space:nowrap">local ''variable-list'' = [[#expression-list|''expression-list'']]</code>
 
<!--T:162-->
Local variables may be declared anywhere within a [[#block|block]] or [[#block|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 [[#Assignments|Assignments]] above.
 
<!--T:163-->
Note that visibility of the local variable begins with the statement after the local variable declaration. So a declaration like <code style="white-space:nowrap">local x = x</code> declares a local variable x and assigns it the value of x from the outer scope. The local variable remains in scope until the end of the innermost block containing the local variable declaration.
 
==== Control structures ==== <!--T:164-->
 
<!--T:165-->
{{Anchor|while}}
<code style="white-space:nowrap">while ''exp'' do ''[[#block|block]]'' end</code>
 
<!--T:166-->
The while statement repeats a block as long as an expression evaluates to a true value.
 
<!--T:167-->
{{Anchor|repeat}}
<code style="white-space:nowrap">repeat ''[[#block|block]]'' until ''exp''</code>
 
<!--T:168-->
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.
 
<!--T:169-->
{{Anchor|for}}
<code style="white-space:nowrap">for ''name'' = ''exp1'', ''exp2'', ''exp3'' do ''[[#block|block]]'' end</code><br>
<code style="white-space:nowrap">for ''name'' = ''exp1'', ''exp2'' do ''[[#block|block]]'' end</code>
 
<!--T:170-->
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 <code>nil</code> and <code>false</code> are an error. All expressions are evaluated once before the loop is started.
 
<!--T:171-->
This form of the for loop is roughly equivalent to
 
<!--T:172-->
do
do
local var, limit, step = tonumber( ''exp1'' ), tonumber( ''exp2'' ), tonumber( ''exp3'' )
if not ( var and limit and step ) then error() end
Line 590 ⟶ 731:
end
 
<!--T:173-->
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.
 
<!--T:174-->
{{Anchor|iterators}}
<code style="white-space:nowrap">for ''var-list'' in [[#expression-list|''expression-list'']] do ''[[#block|block]]'' end</code>
 
<!--T:175-->
The second form of the for loop works with ''iterator'' functions. As in the first form, the ''expresssion-list'' is evaluated only once before beginning the loop.
 
<!--T:176-->
This form of the for loop is roughly equivalent to
 
<!--T:177-->
do
do
local func, static, var = ''expression-list''
while true do
Line 609 ⟶ 755:
end
 
<!--T:178-->
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.
 
<!--T:179-->
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, [http://www.lua.org/pil/7.4.html Programming in Lua] suggests that a closure be preferred to returning a table as the static variable and updating its members on each iteration.
 
<!--T:180-->
{{Anchor|if}}
<code style="white-space:nowrap">if ''exp1'' then ''[[#block|block1]]'' elseif ''exp2'' then ''[[#block|block2]]'' else ''[[#block|block3]]'' end</code>
 
<!--T:181-->
Executes ''block1'' if ''exp1'' returns true, otherwise executes ''block2'' if ''exp2'' returns true, and ''block3'' otherwise. The <code style="white-space:nowrap">else ''block3''</code> portion may be omitted, and the <code style="white-space:nowrap">elseif ''exp2'' then ''block2''</code> portion may be repeated or omitted as necessary.
 
<!--T:182-->
{{Anchor|return}}
<code style="white-space:nowrap">return [[#expression-list|''expression-list'']]</code>
 
<!--T:183-->
The return statement is used to return values from a function or a [[#chunk|chunk]] (which is just a function). The ''expression-list'' is a comma-separated list of zero or more expressions.
 
<!--T:184-->
Lua implements [[:en:tail call|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 [[#getfenv|<code>getfenv()</code>]] and [[#debug.traceback|<code>debug.traceback()</code>]].
 
<!--T:185-->
The return statement must be the last statement in its [[#block|block]]. If for some reason a return is needed in the middle of a block, an explicit block <code style="white-space:nowrap">do return end</code> may be used.
 
<!--T:186-->
{{Anchor|break}}
<code>break</code>
 
<!--T:187-->
The break statement is used to terminate the execution of a while, repeat, or for loop, skipping to the next statement after the loop.
 
<!--T:188-->
The break statement must be the last statement in its [[#block|block]]. If for some reason a break is needed in the middle of a block, an explicit block <code style="white-space:nowrap">do break end</code> may be used.
 
==== Function calls as statements ==== <!--T:189-->
 
<!--T:190-->
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. [[#mw.log|mw.log()]] logs values) and any return values are discarded.
 
==== Function declaration statements ==== <!--T:191-->
 
<!--T:192-->
Lua provides syntactic sugar to make declaring a function and assigning it to a variable more natural. The following pairs of declarations are equivalent
 
<!--T:193-->
-- Basic declaration
function func( ''var-list'' ) ''[[#block|block]]'' end
func = function ( ''var-list'' ) ''[[#block|block]]'' end
 
<!--T:194-->
-- Local function
-- Local function
local function func( ''var-list'' ) ''[[#block|block]]'' end
local func; func = function ( ''var-list'' ) ''[[#block|block]]'' end
 
<!--T:195-->
-- Function as a field in a table
-- Function as a field in a table
function table.func( ''var-list'' ) ''[[#block|block]]'' end
table.func = function ( ''var-list'' ) ''[[#block|block]]'' end
 
<!--T:196-->
-- Function as a method in a table
-- Function as a method in a table
function table:func( ''var-list'' ) ''[[#block|block]]'' end
table.func = function ( self, ''var-list'' ) ''[[#block|block]]'' end
 
<!--T:197-->
Note the colon notation here parallels the colon notation for function calls, adding an implicit argument named "self" at the beginning of the arguments list.
 
=== Error handling === <!--T:198-->
 
<!--T:199-->
Errors may be "thrown" using the [[#error|error()]] and [[#assert|assert()]] functions. To "catch" errors, use [[#pcall|pcall()]] or [[#xpcall|xpcall()]]. Note that certain internal Scribunto errors cannot be caught in Lua code.
 
=== Garbage collection === <!--T:200-->
 
<!--T:201-->
Lua performs automatic memory management. This means that you have to worry neither about allocating memory for new objects nor about freeing it when the objects are no longer needed. Lua manages memory automatically by running a ''garbage collector'' from time to time to collect all dead objects (that is, objects that are no longer accessible from Lua) and objects that are only reachable via [[#weak tables|weak references]]. All memory used by Lua is subject to automatic management: tables, functions, strings, etc.
 
<!--T:202-->
Garbage collection happens automatically, and cannot be configured from within Scribunto.
 
== Standard libraries == <!--T:203-->
 
<!--T:204-->
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 === <!--T:205-->
 
==== _G ==== <!--T:206-->
<span id="_G"></span>
 
<!--T:207-->
This variable holds a reference to the current global variable table; the global variable <code>foo</code> may also be accessed as <code>_G.foo</code>. Note, however, that there is nothing special about _G itself; it may be reassigned in the same manner as any other variable:
 
<!--T:208-->
<syntaxhighlight lang="lua">
foo = 1
Line 691 ⟶ 861:
</syntaxhighlight>
 
<!--T:209-->
The global variable table may be used just like any other table. For example,
 
<!--T:210-->
<syntaxhighlight lang="lua">
-- Call a function whose name is stored in a variable
_G[var]()
 
<!--T:211-->
-- Log the names and stringified values of all global variables
for k, v in pairs( _G ) do
Line 702 ⟶ 875:
end
 
<!--T:212-->
-- Log the creation of new global variables
setmetatable( _G, {
Line 711 ⟶ 885:
</syntaxhighlight>
 
==== _VERSION ==== <!--T:213-->
<span id="_VERSION"></span>
 
<!--T:214-->
A string containing the running version of Lua, e.g. "Lua 5.1".
 
==== assert ==== <!--T:215-->
 
<!--T:216-->
<code style="white-space:nowrap">assert( v, message, ... )</code>
 
<!--T:217-->
If <code>v</code> is nil or false, issues an error. In this case, <code>message</code> 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.
 
<!--T:218-->
If <code>v</code> is any other value, assert returns all arguments including <code>v</code> and <code>message</code>.
 
<!--T:219-->
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 <code>assert</code>:
 
<!--T:220-->
<syntaxhighlight lang="lua">
-- This doesn't check for errors
local result1, result2, etc = func( ... )
 
<!--T:221-->
-- This works the same, but does check for errors
local result1, result2, etc = assert( func( ... ) )
</syntaxhighlight>
 
==== error ==== <!--T:222-->
 
<!--T:223-->
<code style="white-space:nowrap">error( message, level )</code>
 
<!--T:224-->
Issues an error, with text <code>message</code>.
 
<!--T:225-->
<code>error</code> normally adds some information about the location of the error. If <code>level</code> is 1 or omitted, that information is the location of the call to <code>error</code> itself; 2 uses the location of the call of the function that called error; and so on. Passing 0 omits inclusion of the location information.
 
==== getfenv ==== <!--T:226-->
 
<!--T:227-->
<code style="white-space:nowrap">getfenv( f )</code>
 
<!--T:228-->
Note this function may not be available, depending on <code>allowEnvFuncs</code> in the engine configuration.
 
<!--T:229-->
Returns an ''environment'' (global variable table), as specified by <code>f</code>:
* If 1, nil, or omitted, returns the environment of the function calling <code>getfenv</code>. Often this will be the same as [[#_G|_G]].
Line 753 ⟶ 940:
* Passing a function returns the environment that will be used when that function is called.
 
<!--T:230-->
The environments used by all standard library functions and Scribunto library functions are protected. Attempting to access these environments using <code>getfenv</code> will return nil instead.
 
==== getmetatable ==== <!--T:231-->
 
<!--T:232-->
<code style="white-space:nowrap">getmetatable( table )</code>
 
<!--T:233-->
Returns the [[#Metatables|metatable]] of a [[#table|table]]. Any other type will return nil.
 
<!--T:234-->
If the metatable has a <code>__metatable</code> field, that value will be returned instead of the actual metatable.
 
==== ipairs ==== <!--T:235-->
 
<!--T:236-->
<code style="white-space:nowrap">ipairs( t )</code>
 
<!--T:237-->
Returns three values: an iterator function, the table <code>t</code>, and 0. This is intended for use in the [[#iterators|iterator form of <code>for</code>]]:
 
<!--T:238-->
for i, v in ipairs( t ) do
for i, v in ipairs( t ) do
''block''
end
 
<!--T:239-->
This will iterate over the pairs ( 1, t[1] ), ( 2, t[2] ), and so on, stopping when t[i] would be nil.
 
<!--T:240-->
The standard behavior may be overridden by providing an <code>__ipairs</code> [[#Metatables|metamethod]]. If that metamethod exists, the call to ipairs will return the three values returned by <code style="white-space:nowrap">__ipairs( t )</code> instead.
 
==== next ==== <!--T:241-->
 
<!--T:242-->
<code style="white-space:nowrap">next( table, key )</code>
 
<!--T:243-->
This allows for iterating over the keys in a table. If <code>key</code> 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 <code style="white-space:nowrap">next( t ) == nil</code>.
 
<!--T:244-->
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 [[#for|numerical for]] or [[#ipairs|ipairs]].
 
<!--T:245-->
Behavior is undefined if, when using next for traversal, any non-existing key is assigned a value. Assigning a new value (including nil) to an existing field is allowed.
 
==== pairs ==== <!--T:246-->
 
<!--T:247-->
<code style="white-space:nowrap">pairs( t )</code>
 
<!--T:248-->
Returns three values: an iterator function ([[#next|next]] or a work-alike), the table <code>t</code>, and nil. This is intended for use in the [[#iterators|iterator form of <code>for</code>]]:
 
<!--T:249-->
<syntaxhighlight lang="lua">
for k, v in pairs( t ) do
Line 799 ⟶ 1,002:
</syntaxhighlight>
 
<!--T:250-->
This will iterate over the key-value pairs in <code>t</code> just as [[#next|next]] would; see the documentation for [[#next|next]] for restrictions on modifying the table during traversal.
 
<!--T:251-->
The standard behavior may be overridden by providing a __pairs [[#Metatables|metamethod]]. If that metamethod exists, the call to pairs will return the three values returned by <code style="white-space:nowrap">__pairs( t )</code> instead.
 
==== pcall ==== <!--T:252-->
 
<!--T:253-->
<code style="white-space:nowrap">pcall( f, ... )</code>
 
<!--T:254-->
Calls the function <code>f</code> with the given arguments in ''protected mode''. This means that if an error is raised during the call to <code>f</code>, pcall will return false and the error message raised. If no error occurs, pcall will return true and all values returned by the call.
 
<!--T:255-->
In [[:en:pseudocode|pseudocode]], <code>pcall</code> might be defined something like this:
 
<!--T:256-->
<syntaxhighlight lang="lua">
function pcall( f, ... )
Line 821 ⟶ 1,030:
</syntaxhighlight>
 
==== rawequal ==== <!--T:257-->
 
<!--T:258-->
<code style="white-space:nowrap">rawequal( a, b )</code>
 
<!--T:259-->
This is equivalent to <code style="white-space:nowrap">a == b</code> except that it ignores any __eq [[#Metatables|metamethod]].
 
==== rawget ==== <!--T:260-->
 
<!--T:261-->
<code style="white-space:nowrap">rawget( table, k )</code>
 
<!--T:262-->
This is equivalent to <code>table[k]</code> except that it ignores any __index [[#Metatables|metamethod]].
 
==== rawset ==== <!--T:263-->
 
<!--T:264-->
<code style="white-space:nowrap">rawset( table, k, v )</code>
 
<!--T:265-->
This is equivalent to <code style="white-space:nowrap">table[k] = v</code> except that it ignores any __newindex [[#Metatables|metamethod]].
 
==== select ==== <!--T:266-->
 
<!--T:267-->
<code style="white-space:nowrap">select( index, ... )</code>
 
<!--T:268-->
If <code>index</code> is a number, returns all arguments in <code>...</code> after that index. If <code>index</code> is the string '#', returns the count of arguments in <code>...</code>.
 
<!--T:269-->
In other words, <code>select</code> is something roughly like the following except that it will work correctly even when <code>...</code> contains nil values (see documentation for [[#Length operator|#]] and [[#unpack|unpack]] for the problem with nils).
 
<!--T:270-->
<syntaxhighlight lang="lua">
function select( index, ... )
Line 858 ⟶ 1,077:
</syntaxhighlight>
 
==== setmetatable ==== <!--T:271-->
 
<!--T:272-->
<code style="white-space:nowrap">setmetatable( table, metatable )</code>
 
<!--T:273-->
Sets the [[#Metatables|metatable]] of a [[#table|table]]. <code>metatable</code> may be nil, but must be explicitly provided.
 
<!--T:274-->
If the current metatable has a __metatable field, <code>setmetatable</code> will throw an error.
 
==== tonumber ==== <!--T:275-->
 
<!--T:276-->
<code style="white-space:nowrap">tonumber( value, base )</code>
 
<!--T:277-->
Tries to convert <code>value</code> to a number. If it is already a number or a string convertible to a number, then <code>tonumber</code> returns this number; otherwise, it returns nil.
 
<!--T:278-->
The optional <code>base</code> (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.
 
<!--T:279-->
In base 10, the value may have a decimal part, be expressed in [[:en:E notation|E notation]], and may have a leading "0x" to indicate base 16. In other bases, only unsigned integers are accepted.
 
==== tostring ==== <!--T:280-->
 
<!--T:281-->
<code style="white-space:nowrap">tostring( value )</code>
 
<!--T:282-->
Converts <code>value</code> to a string. See [[#Data types|Data types]] above for details on how each type is converted.
 
<!--T:283-->
The standard behavior for tables may be overridden by providing a __tostring [[#Metatables|metamethod]]. If that metamethod exists, the call to tostring will return the single value returned by <code style="white-space:nowrap">__tostring( value )</code> instead.
 
==== type ==== <!--T:284-->
 
<!--T:285-->
<code style="white-space:nowrap">type( value )</code>
 
<!--T:286-->
Returns the type of <code>value</code> as a string: "[[#nil|nil]]", "[[#number|number]]", "[[#string|string]]", "[[#boolean|boolean]]", "[[#table|table]]", or "[[#function|function]]".
 
==== unpack ==== <!--T:287-->
 
<!--T:288-->
<code style="white-space:nowrap">unpack( table, i, j )</code>
 
<!--T:289-->
Returns values from the given table, something like <code style="white-space:nowrap">table[i], table[i+1], ···, table[j]</code> would do if written out manually. If nil or not given, <code>i</code> defaults to 1 and <code>j</code> defaults to <code style="white-space:nowrap">[[#Length operator|#]]table</code>.
 
<!--T:290-->
Note that results are not deterministic if <code>table</code> is not a [[#sequence|sequence]] and <code>j</code> is nil or unspecified; see [[#Length operator|Length operator]] for details.
 
==== xpcall ==== <!--T:291-->
 
<!--T:292-->
<code style="white-space:nowrap">xpcall( f, errhandler )</code>
 
<!--T:293-->
This is much like [[#pcall|<code>pcall</code>]], except that the error message is passed to the function <code>errhandler</code> before being returned.
 
<!--T:294-->
In [[:en:pseudocode|pseudocode]], <code>xpcall</code> might be defined something like this:
 
<!--T:295-->
<syntaxhighlight lang="lua">
function xpcall( f, errhandler )
Line 917 ⟶ 1,155:
</syntaxhighlight>
 
=== Debug library === <!--T:296-->
 
==== debug.traceback ==== <!--T:297-->
 
<!--T:298-->
<code style="white-space:nowrap">debug.traceback( message, level )</code>
 
<!--T:299-->
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 === <!--T:300-->
 
==== math.abs ==== <!--T:301-->
 
<!--T:302-->
<code style="white-space:nowrap">math.abs( x )</code>
 
<!--T:303-->
Returns the absolute value of <code>x</code>.
 
==== math.acos ==== <!--T:304-->
 
<!--T:305-->
<code style="white-space:nowrap">math.acos( x )</code>
 
<!--T:306-->
Returns the arc cosine of <code>x</code> (given in radians).
 
==== math.asin ==== <!--T:307-->
 
<!--T:308-->
<code style="white-space:nowrap">math.asin( x )</code>
 
<!--T:309-->
Returns the arc sine of <code>x</code> (given in radians).
 
==== math.atan ==== <!--T:310-->
 
<!--T:311-->
<code style="white-space:nowrap">math.atan( x )</code>
 
<!--T:312-->
Returns the arc tangent of <code>x</code> (given in radians).
 
==== math.atan2 ==== <!--T:313-->
 
<!--T:314-->
<code style="white-space:nowrap">math.atan2( y, x )</code>
 
<!--T:315-->
Returns the arc tangent of <code>y/x</code> (given in radians), using the signs of both parameters to find the
quadrant of the result.
 
==== math.ceil ==== <!--T:316-->
 
<!--T:317-->
<code style="white-space:nowrap">math.ceil( x )</code>
 
<!--T:318-->
Returns the smallest integer larger than or equal to <code>x</code>.
 
==== math.cos ==== <!--T:319-->
 
<!--T:320-->
<code style="white-space:nowrap">math.cos( x )</code>
 
<!--T:321-->
Returns the cosine of <code>x</code> (given in radians).
 
==== math.cosh ==== <!--T:322-->
 
<!--T:323-->
<code style="white-space:nowrap">math.cosh( x )</code>
 
<!--T:324-->
Returns the hyperbolic cosine of <code>x</code>.
 
==== math.deg ==== <!--T:325-->
 
<!--T:326-->
<code style="white-space:nowrap">math.deg( x )</code>
 
<!--T:327-->
Returns the angle <code>x</code> (given in radians) in degrees.
 
==== math.exp ==== <!--T:328-->
 
<!--T:329-->
<code style="white-space:nowrap">math.exp( x )</code>
 
<!--T:330-->
Returns the value <math>e^x</math>.
 
==== math.floor ==== <!--T:331-->
 
<!--T:332-->
<code style="white-space:nowrap">math.floor( x )</code>
 
<!--T:333-->
Returns the largest integer smaller than or equal to <code>x</code>.
 
==== math.fmod ==== <!--T:334-->
 
<!--T:335-->
<code style="white-space:nowrap">math.fmod( x, y )</code>
 
<!--T:336-->
Returns the remainder of the division of <code>x</code> by <code>y</code> that rounds the quotient towards zero.
 
==== math.frexp ==== <!--T:337-->
 
<!--T:338-->
<code style="white-space:nowrap">math.frexp( x )</code>
 
<!--T:339-->
Returns two values <code>m</code> and <code>e</code> such that:
* If <code>x</code> is finite and non-zero: <math>x = m \times 2^e</math>, <code>e</code> is an integer, and the absolute value of <code>m</code> is in the range <math>[0.5, 1)</math>
Line 1,009 ⟶ 1,275:
* If <code>x</code> is NaN or infinite: <code>m</code> is <code>x</code> and <code>e</code> is not specified
 
==== math.huge ==== <!--T:340-->
 
<!--T:341-->
The value representing positive infinity; larger than or equal to any other numerical value.
 
==== math.ldexp ==== <!--T:342-->
 
<!--T:343-->
<code style="white-space:nowrap">math.ldexp( m, e )</code>
 
<!--T:344-->
Returns <math>m \times 2^e</math> (<code>e</code> should be an integer).
 
==== math.log ==== <!--T:345-->
 
<!--T:346-->
<code style="white-space:nowrap">math.log( x )</code>
 
<!--T:347-->
Returns the natural logarithm of <code>x</code>.
 
==== math.log10 ==== <!--T:348-->
 
<!--T:349-->
<code style="white-space:nowrap">math.log10( x )</code>
 
<!--T:350-->
Returns the base-10 logarithm of <code>x</code>.
 
==== math.max ==== <!--T:351-->
 
<!--T:352-->
<code style="white-space:nowrap">math.max( x, ... )</code>
 
<!--T:353-->
Returns the maximum value among its arguments.
 
<!--T:354-->
Behavior with NaNs is not specified. With the current implementation, NaN will be returned if <code>x</code> is NaN, but any other NaNs will be ignored.
 
==== math.min ==== <!--T:355-->
 
<!--T:356-->
<code style="white-space:nowrap">math.min( x, ... )</code>
 
<!--T:357-->
Returns the minimum value among its arguments.
 
<!--T:358-->
Behavior with NaNs is not specified. With the current implementation, NaN will be returned if <code>x</code> is NaN, but any other NaNs will be ignored.
 
==== math.modf ==== <!--T:359-->
 
<!--T:360-->
<code style="white-space:nowrap">math.modf( x )</code>
 
<!--T:361-->
Returns two numbers, the integral part of <code>x</code> and the fractional part of <code>x</code>.
 
==== math.pi ==== <!--T:362-->
 
<!--T:363-->
The value of <math>\pi</math>.
 
==== math.pow ==== <!--T:364-->
 
<!--T:365-->
<code style="white-space:nowrap">math.pow( x, y )</code>
 
<!--T:366-->
Equivalent to <code>x^y</code>.
 
==== math.rad ==== <!--T:367-->
 
<!--T:368-->
<code style="white-space:nowrap">math.rad( x )</code>
 
<!--T:369-->
Returns the angle <code>x</code> (given in degrees) in radians.
 
==== math.random ==== <!--T:370-->
 
<!--T:371-->
<code style="white-space:nowrap">math.random( m, n )</code>
 
<!--T:372-->
Returns a pseudo-random number.
 
<!--T:373-->
The arguments <code>m</code> and <code>n</code> may be omitted, but if specified must be convertible to integers.
* With no arguments, returns a real number in the range <math>[0,1)</math>
Line 1,080 ⟶ 1,369:
* With two arguments, returns an integer in the range <math>[m,n]</math>
 
==== math.randomseed ==== <!--T:374-->
 
<!--T:375-->
<code style="white-space:nowrap">math.randomseed( x )</code>
 
<!--T:376-->
Sets <code>x</code> as the [[:en:Random seed|seed]] for the pseudo-random generator.
 
<!--T:377-->
Note that using the same seed will cause <code>math.random</code> to output the same sequence of numbers.
 
==== math.sin ==== <!--T:378-->
 
<!--T:379-->
<code style="white-space:nowrap">math.sin( x )</code>
 
<!--T:380-->
Returns the sine of <code>x</code> (given in radians).
 
==== math.sinh ==== <!--T:381-->
 
<!--T:382-->
<code style="white-space:nowrap">math.sinh( x )</code>
 
<!--T:383-->
Returns the hyperbolic sine of <code>x</code>.
 
==== math.sqrt ==== <!--T:384-->
 
<!--T:385-->
<code style="white-space:nowrap">math.sqrt( x )</code>
 
<!--T:386-->
Returns the square root of <code>x</code>. Equivalent to <code>x^0.5</code>.
 
==== math.tan ==== <!--T:387-->
 
<!--T:388-->
<code style="white-space:nowrap">math.tan( x )</code>
 
<!--T:389-->
Returns the tangent of <code>x</code> (given in radians).
 
==== math.tanh ==== <!--T:390-->
 
<!--T:391-->
<code style="white-space:nowrap">math.tanh( x )</code>
 
<!--T:392-->
Returns the hyperbolic tangent of <code>x</code>.
 
=== Operating system library === <!--T:393-->
 
==== os.clock ==== <!--T:394-->
 
<!--T:395-->
<code>os.clock()</code>
 
<!--T:396-->
Returns an approximation of the amount in seconds of CPU time used by the program.
 
==== os.date ==== <!--T:397-->
 
<!--T:398-->
<code style="white-space:nowrap">os.date( format, time )</code>
 
<!--T:399-->
: ''[[#mw.language:formatDate|Language library's formatDate]] may be used for more comprehensive date formatting''
 
<!--T:400-->
Returns a string or a table containing date and time, formatted according to <code>format</code>. If the format is omitted or nil, "%c" is used.
 
<!--T:401-->
If <code>time</code> is given, it is the time to be formatted (see <code>[[#os.time|os.time()]]</code>). Otherwise the current time is used.
 
<!--T:402-->
If <code>format</code> starts with '!', then the date is formatted in UTC rather than the server's local time. After this optional character, if format is the string "*t", then date returns a table with the following fields:
* year (full)
Line 1,147 ⟶ 1,456:
* isdst (daylight saving flag, a boolean; may be absent if the information is not available)
 
<!--T:403-->
If format is not "*t", then date returns the date as a string, formatted according to the same rules as the C function [http://man7.org/linux/man-pages/man3/strftime.3.html strftime].
 
==== os.difftime ==== <!--T:404-->
 
<!--T:405-->
<code style="white-space:nowrap">os.difftime( t2, t1 )</code>
 
<!--T:406-->
Returns the number of seconds from <code>t1</code> to <code>t2</code>.
 
==== os.time ==== <!--T:407-->
 
<!--T:408-->
<code style="white-space:nowrap">os.time( table )</code>
 
<!--T:409-->
Returns a number representing the current time.
 
<!--T:410-->
When called without arguments, returns the current time. If passed a table, the time encoded in the table will be parsed. The table must have the fields "year", "month", and "day", and may also include "hour" (default 12), "min" (default 0), "sec" (default 0), and "isdst".
 
=== Package library === <!--T:411-->
 
==== require ==== <!--T:412-->
 
<!--T:413-->
<code style="white-space:nowrap">require( modulename )</code>
 
<!--T:414-->
Loads the specified module.
 
<!--T:415-->
First, it looks in <code>package.loaded[modulename]</code> to see if the module is already loaded. If so, returns <code>package.loaded[modulename]</code>.
 
<!--T:416-->
Otherwise, it calls each loader in the <code>package.loaders</code> 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 <code>package.loaded[modulename]</code> and is returned.
 
<!--T:417-->
See the documentation for [[#package.loaders|<code>package.loaders</code>]] for information on the loaders available.
 
<!--T:418-->
Note that every required module is loaded in its own sandboxed environment, so it cannot export global variables as is sometimes done in Lua 5.1. Instead, everything that the module wishes to export should be included in the table returned by the module.
 
 
<!--T:419-->
For example, if you have a module "Module:Giving" containing the following:
 
<!--T:420-->
<syntaxhighlight lang="lua">
local p = {}
 
<!--T:421-->
p.someDataValue = 'Hello!'
 
<!--T:422-->
return p
</syntaxhighlight>
 
<!--T:423-->
You can load this in another module with code such as this:
 
<!--T:424-->
<syntaxhighlight lang="lua">
local giving = require( "Module:Giving" )
 
<!--T:425-->
local value = giving.someDataValue -- value is now 'Hello!'
</syntaxhighlight>
 
==== package.loaded ==== <!--T:426-->
 
<!--T:427-->
This table holds the loaded modules. The keys are the module names, and the values are the values returned when the module was loaded.
 
==== package.loaders ==== <!--T:428-->
 
<!--T:429-->
This table holds the sequence of searcher functions to use when loading modules. Each searcher function is called with a single argument, the name of the module to load. If the module is found, the searcher must return a function that will actually load the module and return the value to be returned by [[#require|require]]. Otherwise, it must return nil.
 
<!--T:430-->
Scribunto provides two searchers:
# Look in <code>package.preload[modulename]</code> for the loader function
# Look in the [[#Loadable libraries|modules provided with Scribunto]] for the module name, and if that fails look in the Module: namespace. The "Module:" prefix must be provided.
 
<!--T:431-->
Note that the standard Lua loaders are '''not''' included.
 
==== package.preload ==== <!--T:432-->
 
<!--T:433-->
This table holds loader functions, used by the first searcher Scribunto includes in [[#package.loaders|package.loaders]].
 
==== package.seeall ==== <!--T:434-->
 
<!--T:435-->
<code style="white-space:nowrap">package.seeall( table )</code>
 
<!--T:436-->
Sets the __index [[#Metatables|metamethod]] for <code>table</code> to [[#_G|_G]].
 
=== String library === <!--T:437-->
 
<!--T:438-->
In all string functions, the first character is at position&nbsp;1, not position&nbsp;0 as in C, PHP, and JavaScript. Indexes may be negative, in which case they count from the end of the string: position&nbsp;-1 is the last character in the string, -2 is the second-last, and so on.
 
<!--T:439-->
{{red|Warning:}} The string library assumes one-byte character encodings. '''It cannot handle Unicode characters'''. To operate on Unicode strings, use the corresponding methods in the [[#Ustring library|Scribunto Ustring library]].
 
==== string.byte ==== <!--T:440-->
 
<!--T:441-->
<code style="white-space:nowrap">string.byte( s, i, j )</code>
 
<!--T:442-->
If the string is considered as an array of bytes, returns the byte values for <code>s[i]</code>, <code>s[i+1]</code>, ···, <code>s[j]</code>.
The default value for <code>i</code> is&nbsp;1;
Line 1,237 ⟶ 1,576:
Identical to [[#mw.ustring.byte|mw.ustring.byte()]].
 
==== string.char ==== <!--T:443-->
 
<!--T:444-->
<code style="white-space:nowrap">string.char( ... )</code>
 
<!--T:445-->
Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the byte value equal to its corresponding argument. See [[#mw.ustring.char|mw.ustring.char()]] for a similar function that uses Unicode codepoints rather than byte values.
 
==== string.find ==== <!--T:446-->
 
<!--T:447-->
<code style="white-space:nowrap">string.find( s, pattern, init, plain )</code>
 
<!--T:448-->
Looks for the first match of [[#Patterns|<code>pattern</code>]] in the string <code>s</code>. If it finds a match, then <code>find</code> returns the offsets in&nbsp;<code>s</code> 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.
 
<!--T:449-->
A third, optional numerical argument <code>init</code> specifies where to start the search; its default value is&nbsp;1 and can be negative. A value of true as a fourth, optional argument <code>plain</code> turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in <code>pattern</code> being considered "magic".
 
<!--T:450-->
Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
 
<!--T:451-->
See [[#mw.ustring.find|mw.ustring.find()]] for a similar function extended as described in [[#Ustring patterns|Ustring patterns]] and where the <code>init</code> offset is in characters rather than bytes.
 
==== string.format ==== <!--T:452-->
 
<!--T:453-->
<code style="white-space:nowrap">string.format( formatstring, ... )</code>
 
<!--T:454-->
Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string).
 
<!--T:455-->
The format string uses a limited subset of the [http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html <code>printf</code> format specifiers]:
* Recognized flags are '-', '+', ' ', '#', and '0'.
Line 1,269 ⟶ 1,618:
* Positional specifiers (e.g. "%2$s") are not supported.
 
<!--T:456-->
The conversion specifier 'q' is like 's', but formats the string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written.
 
<!--T:457-->
Conversion between strings and numbers is performed as specified in [[#Data types|Data types]]; other types are not automatically converted to strings. Strings containing NUL characters (byte value 0) are not properly handled.
 
<!--T:458-->
Identical to [[#mw.ustring.format|mw.ustring.format()]].
 
==== string.gmatch ==== <!--T:459-->
 
<!--T:460-->
<code style="white-space:nowrap">string.gmatch( s, pattern )</code>
 
<!--T:461-->
Returns an iterator function that, each time it is called, returns the next captures from [[#Patterns|<code>pattern</code>]] over string <code>s</code>. If <code>pattern</code> specifies no captures, then the whole match is produced in each call.
 
<!--T:462-->
For this function, a '<code>^</code>' at the start of a pattern is not magic, as this would prevent the iteration. It is treated as a literal character.
 
<!--T:463-->
See [[#mw.ustring.gmatch|mw.ustring.gmatch()]] for a similar function for which the pattern is extended as described in [[#Ustring patterns|Ustring patterns]].
 
==== string.gsub ==== <!--T:464-->
 
<!--T:465-->
<code style="white-space:nowrap">string.gsub( s, pattern, repl, n )</code>
 
<!--T:466-->
Returns a copy of <code>s</code> in which all (or the first <code>n</code>, if given) occurrences of the [[#Patterns|<code>pattern</code>]] have been replaced by a replacement string specified by <code>repl</code>, which can be a string, a table, or a function. <code>gsub</code> also returns, as its second value, the total number of matches that occurred.
 
<!--T:467-->
If <code>repl</code> is a string, then its value is used for replacement. The character&nbsp;<code>%</code> works as an escape character: any sequence in <code>repl</code> of the form <code>%''n''</code>,
with ''n'' between 1 and 9, stands for the value of the ''n''-th captured substring. The sequence <code>%0</code> stands for the whole match, and the sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
 
<!--T:468-->
If <code>repl</code> 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.
 
<!--T:469-->
If <code>repl</code> 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.
 
<!--T:470-->
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).
 
<!--T:471-->
See [[#mw.ustring.gsub|mw.ustring.gsub()]] for a similar function in which the pattern is extended as described in [[#Ustring patterns|Ustring patterns]].
 
==== string.len ==== <!--T:472-->
 
<!--T:473-->
<code style="white-space:nowrap">string.len( s )</code>
 
<!--T:474-->
Returns the length of the string, in bytes. Is not confused by ASCII NUL characters. Equivalent to <code style="white-space:nowrap">[[#Length operator|#]]s</code>.
 
<!--T:475-->
See [[#mw.ustring.len|mw.ustring.len()]] for a similar function using Unicode codepoints rather than bytes.
 
==== string.lower ==== <!--T:476-->
 
<!--T:477-->
<code style="white-space:nowrap">string.lower( s )</code>
 
<!--T:478-->
Returns a copy of this string with all ASCII uppercase letters changed to lowercase. All other characters are left unchanged.
 
<!--T:479-->
See [[#mw.ustring.lower|mw.ustring.lower()]] for a similar function in which all characters with uppercase to lowercase definitions in Unicode are converted.
 
==== string.match ==== <!--T:480-->
 
<!--T:481-->
<code style="white-space:nowrap">string.match( s, pattern, init )</code>
 
<!--T:482-->
Looks for the first match of [[#Patterns|<code>pattern</code>]] in the string. If it finds one, then <code>match</code> returns the captures from the pattern; otherwise it returns nil. If <code>pattern</code> specifies no captures, then the whole match is returned.
 
<!--T:483-->
A third, optional numerical argument <code>init</code> specifies where to start the search; its default value is&nbsp;1 and can be negative.
 
<!--T:484-->
See [[#mw.ustring.match|mw.ustring.match()]] for a similar function in which the pattern is extended as described in [[#Ustring patterns|Ustring patterns]] and the <code>init</code> offset is in characters rather than bytes.
 
==== string.rep ==== <!--T:485-->
 
<!--T:486-->
<code style="white-space:nowrap">string.rep( s, n )</code>
 
<!--T:487-->
Returns a string that is the concatenation of <code>n</code> copies of the string <code>s</code>. Identical to [[#mw.ustring.rep|mw.ustring.rep()]].
 
==== string.reverse ==== <!--T:488-->
 
<!--T:489-->
<code style="white-space:nowrap">string.reverse( s )</code>
 
<!--T:490-->
Returns a string that is the string <code>s</code> reversed (bytewise).
 
==== string.sub ==== <!--T:491-->
 
<!--T:492-->
<code style="white-space:nowrap">string.sub( s, i, j )</code>
 
<!--T:493-->
Returns the substring of <code>s</code> that starts at <code>i</code> and continues until <code>j</code>; <code>i</code> and <code>j</code> can be negative. If <code>j</code> is nil or omitted, -1 is used.
 
<!--T:494-->
In particular, the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code> with length <code>j</code>, and <code style="white-space:nowrap">string.sub(s, -i)</code> returns a suffix of <code>s</code> with length <code>i</code>.
 
<!--T:495-->
See [[#mw.ustring.sub|mw.ustring.sub()]] for a similar function in which the offsets are characters rather than bytes.
 
==== string.upper ==== <!--T:496-->
 
<!--T:497-->
<code style="white-space:nowrap">string.upper( s )</code>
 
<!--T:498-->
Returns a copy of this string with all ASCII lowercase letters changed to uppercase. All other characters are left unchanged.
 
<!--T:499-->
See [[#mw.ustring.upper|mw.ustring.upper()]] for a similar function in which all characters with lowercase to uppercase definitions in Unicode are converted.
 
==== Patterns ==== <!--T:500-->
 
<!--T:501-->
Note that Lua's patterns are similar to [[:en:regular expression|regular expressions]], but are not identical. In particular, note the following differences from regular expressions and [[:en:PCRE|PCRE]]:
* The quoting character is percent (<code>%</code>), not backslash (<code>\</code>).
Line 1,372 ⟶ 1,757:
** For example, in PCRE the regexp <code>\x65</code> (from a string literal such as <code>"\\x65"</code>) will match the string "hello", because the PCRE engine interprets escaped characters. But in Lua the equivalent pattern <code>\101</code> (from a string literal such as <code>"\\101"</code>) will not match "hello". -->
 
<!--T:502-->
Also note that a pattern cannot contain embedded zero bytes (ASCII NUL, <code>"\0"</code>). Use <code>%z</code> instead.
 
<!--T:503-->
Also see [[#Ustring patterns|Ustring patterns]] for a similar pattern-matching scheme using Unicode characters.
 
===== Character class ===== <!--T:504-->
 
<!--T:505-->
A ''character class'' is used to represent a set of characters. The following combinations are allowed in describing a character class:
 
<!--T:506-->
* '''''x''''': (where ''x'' is not one of the magic characters <code>^$()%.[]*+-?</code>) represents the character ''x'' itself.
* '''<code>.</code>''': (a dot) represents all characters.
Line 1,406 ⟶ 1,795:
* '''<code>[^''set'']</code>''': represents the complement of ''set'', where ''set'' is interpreted as above.
 
===== Pattern items ===== <!--T:507-->
 
<!--T:508-->
A ''pattern item'' can be
 
<!--T:509-->
* a single character class, which matches any single character in the class;
* a single character class followed by '<code>*</code>', which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
Line 1,420 ⟶ 1,811:
* <code>%f[''set'']</code>, a ''frontier pattern''; such item matches an empty string at any position such that the next character belongs to ''set'' and the previous character does not belong to ''set''. The set ''set'' is interpreted as previously described. The beginning and the end of the subject are handled as if they were the character&nbsp;'\0'.<br><small>Note that frontier patterns were present but undocumented in Lua&nbsp;5.1, and officially added to Lua in 5.2. The implementation in Lua&nbsp;5.2.1 is unchanged from that in 5.1.0.</small>
 
===== Pattern ===== <!--T:510-->
 
<!--T:511-->
A ''pattern'' is a sequence of pattern items.
 
<!--T:512-->
A '<code>^</code>' at the beginning of a pattern anchors the match at the
beginning of the subject string. A '<code>$</code>' at the end of a pattern anchors the match at the
end of the subject string. At other positions, '<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
 
===== Captures ===== <!--T:513-->
 
<!--T:514-->
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 <code>(a*(.)%w(%s*))</code>, the part of the string matching <code>a*(.)%w(%s*)</code> is stored as the first capture (and therefore has number&nbsp;1); the character matching <code>.</code> is captured with number&nbsp;2, and the part matching <code>%s*</code> has number&nbsp;3.
 
<!--T:515-->
Capture references can appear in the pattern string itself, and refer back to text that was captured earlier in the match. For example, <code>([a-z])%1</code> will match any pair of identical lowercase letters, while <code>([a-z])([a-z])([a-z])[a-z]%3%2%1</code> will match any 7-letter [[w:Palindrome|palindrome]].
 
<!--T:516-->
As a special case, the empty capture <code>()</code> captures the current string position (a number). For instance, if we apply the pattern <code>"()aa()"</code> on the string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
 
=== Table library === <!--T:517-->
 
<!--T:518-->
Most functions in the table library assume that the table represents a [[#sequence|sequence]].
 
<!--T:519-->
The functions <code>table.foreach()</code>, <code>table.foreachi()</code>, and <code>table.getn()</code> may be available but are deprecated. Use a for loop with [[#pairs|pairs()]], a for loop with [[#ipairs|ipairs()]], and the length operator instead.
 
==== table.concat ==== <!--T:520-->
 
<!--T:521-->
<code style="white-space:nowrap">table.concat( table, sep, i, j )</code>
 
<!--T:522-->
Given an array where all elements are strings or numbers, returns <code style="white-space:nowrap">table[i] .. sep .. table[i+1] ··· sep .. table[j]</code>.
 
<!--T:523-->
The default value for <code>sep</code> is the empty string, the default for <code>i</code> is 1, and the default for <code>j</code> is the length of the table. If <code>i</code> is greater than <code>j</code>, returns the empty string.
 
==== table.insert ==== <!--T:524-->
 
<!--T:525-->
<code style="white-space:nowrap">table.insert( table, value )</code><br>
<code style="white-space:nowrap">table.insert( table, pos, value )</code>
 
<!--T:526-->
Inserts element <code>value</code> at position <code>pos</code> in <code>table</code>, shifting up other elements to open space, if necessary. The default value for <code>pos</code> is the length of the table plus 1, so that a call <code style="white-space:nowrap">table.insert(t, x)</code> inserts <code>x</code> at the end of table <code>t</code>.
 
<!--T:527-->
Elements up to <code>#table</code> are shifted; see [[#Length operator|Length operator]] for caveats if the table is not a [[#sequence|sequence]].
 
==== table.maxn ==== <!--T:528-->
 
<!--T:529-->
<code style="white-space:nowrap">table.maxn( table )</code>
 
<!--T:530-->
Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices.
 
<!--T:531-->
To do this, it iterates over the whole table. This is roughly equivalent to
 
<!--T:532-->
<syntaxhighlight lang="lua">
function table.maxn( table )
Line 1,480 ⟶ 1,888:
</syntaxhighlight>
 
==== table.remove ==== <!--T:533-->
 
<!--T:534-->
<code style="white-space:nowrap">table.remove( table, pos )</code>
 
<!--T:535-->
Removes from <code>table</code> the element at position <code>pos</code>,
shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for <code>pos</code> is the length of the table, so that a call <code style="white-space:nowrap">table.remove( t )</code> removes the last element of table <code>t</code>.
 
<!--T:536-->
Elements up to <code>#table</code> are shifted; see [[#Length operator|Length operator]] for caveats if the table is not a [[#sequence|sequence]].
 
==== table.sort ==== <!--T:537-->
 
<!--T:538-->
<code style="white-space:nowrap">table.sort( table, comp )</code>
 
<!--T:539-->
Sorts table elements in a given order, ''in-place'', from <code>table[1]</code> to <code>table[#table]</code>. If <code>comp</code> is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that <code style="white-space:nowrap">not comp(a[i+1],a[i])</code> will be true after the sort). If <code>comp</code> is not given, then the standard Lua operator <code>&lt;</code> is used instead.
 
<!--T:540-->
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 == <!--T:541-->
 
<!--T:542-->
All Scribunto libraries are located in the table <code>mw</code>.
 
=== Base functions === <!--T:543-->
 
==== mw.allToString ==== <!--T:544-->
 
<!--T:545-->
<code style="white-space:nowrap">mw.allToString( ... )</code>
 
<!--T:546-->
Calls [[#tostring|tostring()]] on all arguments, then concatenates them with tabs as separators.
 
==== mw.clone ==== <!--T:547-->
 
<!--T:548-->
<code style="white-space:nowrap">mw.clone( value )</code>
 
<!--T:549-->
Creates a deep copy of a value. All tables (and their metatables) are reconstructed from scratch. Functions are still shared, however.
 
==== mw.getCurrentFrame ==== <!--T:550-->
 
<!--T:551-->
<code>mw.getCurrentFrame()</code>
 
<!--T:552-->
Returns the current [[#Frame object|frame object]].
 
==== mw.incrementExpensiveFunctionCount ==== <!--T:553-->
 
<!--T:554-->
<code>mw.incrementExpensiveFunctionCount()</code>
 
<!--T:555-->
Adds one to the "expensive parser function" count, and throws an exception if it exceeds the limit (see [[Manual:$wgExpensiveParserFunctionLimit|$wgExpensiveParserFunctionLimit]]).
 
==== mw.isSubsting ==== <!--T:556-->
 
<!--T:557-->
<code>mw.isSubsting()</code>
 
<!--T:558-->
Returns true if the current <code>#invoke</code> is being [[Manual:Substitution|substed]], false otherwise. See [[#Returning text|Returning text]] above for discussion on differences when substing versus not substing.
 
==== mw.loadData ==== <!--T:559-->
 
<!--T:560-->
<code style="white-space:nowrap">mw.loadData( module )</code>
 
<!--T:561-->
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 <code><nowiki>{{#invoke:}}</nowiki></code> can use a significant amount of time. To avoid this issue, <code>mw.loadData()</code> is provided.
 
<!--T:562-->
<code>mw.loadData</code> works like <code>[[#require|require()]]</code>, with the following differences:
* The loaded module is evaluated only once per page, rather than once per <code><nowiki>{{#invoke:}}</nowiki></code> call.
Line 1,548 ⟶ 1,976:
* The table actually returned by <code>mw.loadData()</code> has metamethods that provide read-only access to the table returned by the module. Since it does not contain the data directly, <code>[[#pairs|pairs()]]</code> and <code>[[#ipairs|ipairs()]]</code> will work but other methods, including <code>[[#Length operator|#value]]</code>, <code style="white-space:nowrap">[[#next|next()]]</code>, and the functions in the [[#Table library|Table library]], will not work correctly.
 
<!--T:563-->
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 <code style="white-space:nowrap">local data = mw.loadData( 'Module:Convert/data' )</code> to efficiently load the data.
 
==== mw.dumpObject ==== <!--T:564-->
 
<!--T:565-->
<code style="white-space:nowrap">mw.dumpObject( object )</code>
 
<!--T:566-->
Serializes <code>object</code> to a human-readable representation, then returns the resulting string.
 
==== mw.log ==== <!--T:567-->
 
<!--T:568-->
{{Anchor|print}}
<code style="white-space:nowrap">mw.log( ... )</code>
 
<!--T:569-->
Passes the arguments to [[#mw.allToString|mw.allToString()]], then appends the resulting string to the log buffer.
 
<!--T:570-->
In the debug console, the function <code>print()</code> is an alias for this function.
 
==== mw.logObject ==== <!--T:571-->
 
<!--T:572-->
<code style="white-space:nowrap">mw.logObject( object )</code><br>
<code style="white-space:nowrap">mw.logObject( object, prefix )</code>
 
<!--T:573-->
Calls [[#mw.dumpObject|mw.dumpObject()]] and appends the resulting string to the log buffer. If <code>prefix</code> is given, it will be added to the log buffer followed by an equals sign before the serialized string is appended (i.e. the logged text will be "prefix = object-string").
 
=== Frame object === <!--T:574-->
 
<!--T:575-->
The frame object is the interface to the parameters passed to <code><nowiki>{{#invoke:}}</nowiki></code>, and to the parser.
 
==== frame.args ==== <!--T:576-->
 
<!--T:577-->
A table for accessing the arguments passed to the frame. For example, if a module is called from wikitext with
 
<!--T:578-->
<nowiki>{{#invoke:module|function|arg1|arg2|name=arg3}}</nowiki>
<nowiki>{{#invoke:module|function|arg1|arg2|name=arg3}}</nowiki>
 
<!--T:579-->
then <code>frame.args[1]</code> will return "arg1", <code>frame.args[2]</code> will return "arg2", and <code>frame.args['name']</code> (or <code>frame.args.name</code>) will return "arg3". It is also possible to iterate over arguments using <code style="white-space:nowrap">pairs( frame.args )</code> or <code style="white-space:nowrap">ipairs( frame.args )</code>.
 
<!--T:580-->
Note that values in this table are always strings; <code>[[#tonumber|tonumber()]]</code> may be used to convert them to numbers, if necessary. Keys, however, are numbers even if explicitly supplied in the invocation: <nowiki>{{#invoke:module|function|1|2=2}}</nowiki> gives string values "1" and "2" indexed by numeric keys 1 and 2.
 
<!--T:581-->
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.
 
<!--T:582-->
For performance reasons, frame.args 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 <code>[[#Length operator|#frame.args]]</code>, <code style="white-space:nowrap">[[#next|next]]( frame.args )</code>, and the functions in the [[#Table library|Table library]].
 
<!--T:583-->
If preprocessor syntax such as template invocations and triple-brace arguments are included within an argument to #invoke, they will be expanded before being passed to Lua. If certain special tags written in XML notation, such as <code>&lt;pre&gt;</code>, <code>&lt;nowiki&gt;</code>, <code>&lt;gallery&gt;</code> and <code>&lt;ref&gt;</code>, are included as arguments to #invoke, then these tags will be converted to "[[strip marker]]s" — special strings which begin with a delete character (ASCII 127), to be replaced with HTML after they are returned from #invoke.
 
==== frame:callParserFunction ==== <!--T:584-->
 
<!--T:585-->
<code style="white-space:nowrap">frame:callParserFunction( name, args )</code><br>
<code style="white-space:nowrap">frame:callParserFunction( name, ... )</code><br>
<code style="white-space:nowrap">frame:callParserFunction{ name = string, args = table }</code>
 
<!--T:586-->
: ''Note the use of [[#named arguments|named arguments]].''
 
<!--T:587-->
Call a [[Help:Magic words#Parser functions|parser function]], returning an appropriate string. Whenever possible, native Lua functions or Scribunto library functions should be preferred to this interface.
 
<!--T:588-->
The following calls are approximately equivalent to the indicated wikitext:
 
<!--T:589-->
<syntaxhighlight lang="lua">
-- {{ns:0}}
frame:callParserFunction{ name = 'ns', args = 0 }
 
<!--T:590-->
-- {{#tag:nowiki|some text}}
frame:callParserFunction{ name = '#tag', args = { 'nowiki', 'some text' } }
Line 1,614 ⟶ 2,064:
frame:callParserFunction( '#tag:nowiki', 'some text' )
 
<!--T:591-->
-- {{#tag:ref|some text|name=foo|group=bar}}
frame:callParserFunction{ name = '#tag:ref', args = {
Line 1,620 ⟶ 2,071:
</syntaxhighlight>
 
<!--T:592-->
Note that, as with [[#frame:expandTemplate|frame:expandTemplate()]], the function name and arguments are not preprocessed before being passed to the parser function.
 
==== frame:expandTemplate ==== <!--T:593-->
 
<!--T:594-->
<code style="white-space:nowrap">frame:expandTemplate{ title = title, args = table }</code>
 
<!--T:595-->
: ''Note the use of [[#named arguments|named arguments]].''
 
<!--T:596-->
This is transclusion. The call
 
<!--T:597-->
frame:expandTemplate{ title = 'template', args = { 'arg1', 'arg2', name = 'arg3' } }
frame:expandTemplate{ title = 'template', args = { 'arg1', 'arg2', name = 'arg3' } }
 
<!--T:598-->
does roughly the same thing from Lua that <code><nowiki>{{template|arg1|arg2|name=arg3}}</nowiki></code> 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.
 
<!--T:599-->
Note that the title and arguments are not preprocessed before being passed into the template:
 
<!--T:600-->
<syntaxhighlight lang="lua">
-- This is roughly equivalent to wikitext like
Line 1,641 ⟶ 2,100:
frame:expandTemplate{ title = 'template', args = { '|' } }
 
<!--T:601-->
-- This is roughly equivalent to wikitext like
-- {{template|{{((}}!{{))}}}}
Line 1,646 ⟶ 2,106:
</syntaxhighlight>
 
==== frame:extensionTag ==== <!--T:602-->
 
<!--T:603-->
<code style="white-space:nowrap">frame:extensionTag( name, content, args )</code><br>
<code style="white-space:nowrap">frame:extensionTag{ name = string, content = string, args = table_or_string }</code>
 
<!--T:604-->
This is equivalent to a call to [[#frame:callParserFunction|frame:callParserFunction()]] with function name <code style="white-space:nowrap">'#tag:' .. name</code> and with <code>content</code> prepended to <code>args</code>.
 
<!--T:605-->
<syntaxhighlight lang="lua">
-- These are equivalent
Line 1,658 ⟶ 2,121:
frame:extensionTag( 'ref', 'some text', { name = 'foo', group = 'bar' } )
 
<!--T:606-->
frame:callParserFunction{ name = '#tag:ref', args = {
'some text', name = 'foo', group = 'bar'
} }
 
<!--T:607-->
-- These are equivalent
frame:extensionTag{ name = 'ref', content = 'some text', args = 'some other text' }
Line 1,670 ⟶ 2,135:
 
 
==== frame:getParent ==== <!--T:608-->
 
<!--T:609-->
<code>frame:getParent()</code>
 
<!--T:610-->
Called on the frame created by <code><nowiki>{{#invoke:}}</nowiki></code>, returns the frame for the page that called <code><nowiki>{{#invoke:}}</nowiki></code>. Called on that frame, returns nil.
 
==== frame:getTitle ==== <!--T:611-->
 
<!--T:612-->
<code>frame:getTitle()</code>
 
<!--T:613-->
Returns the title associated with the frame as a string. For the frame created by <code><nowiki>{{#invoke:}}</nowiki></code>, this is the title of the module invoked.
 
==== frame:newChild ==== <!--T:614-->
 
<!--T:615-->
<code style="white-space:nowrap">frame:newChild{ title = title, args = table }</code>
 
<!--T:616-->
: ''Note the use of [[#named arguments|named arguments]].''
 
<!--T:617-->
Create a new [[#Frame object|Frame object]] that is a child of the current frame, with optional arguments and title.
 
<!--T:618-->
This is mainly intended for use in the debug console for testing functions that would normally be called by <code><nowiki>{{#invoke:}}</nowiki></code>. The number of frames that may be created at any one time is limited.
 
==== frame:preprocess ==== <!--T:619-->
 
<!--T:620-->
<code style="white-space:nowrap">frame:preprocess( string )</code><br>
<code style="white-space:nowrap">frame:preprocess{ text = string }</code>
 
<!--T:621-->
This expands wikitext in the context of the frame, i.e. templates, parser functions, and parameters such as <code><nowiki>{{{1}}}</nowiki></code> are expanded. Certain special tags written in XML-style notation, such as <code>&lt;pre&gt;</code>, <code>&lt;nowiki&gt;</code>, <code>&lt;gallery&gt;</code> and <code>&lt;ref&gt;</code>, will be replaced with "[[strip marker]]s" &mdash; special strings which begin with a delete character (ASCII 127), to be replaced with HTML after they are returned from <code>#invoke</code>.
 
<!--T:622-->
If you are expanding a single template, use [[#frame:expandTemplate|<code>frame:expandTemplate</code>]] 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.
 
==== frame:getArgument ==== <!--T:623-->
 
<!--T:624-->
<code style="white-space:nowrap">frame:getArgument( arg )</code><br>
<code style="white-space:nowrap">frame:getArgument{ name = arg }</code>
 
<!--T:625-->
Gets an object for the specified argument, or nil if the argument is not provided.
 
<!--T:626-->
The returned object has one method, <code>object:expand()</code>, that returns the expanded wikitext for the argument.
 
==== frame:newParserValue ==== <!--T:627-->
 
<!--T:628-->
<code style="white-space:nowrap">frame:newParserValue( text )</code><br>
<code style="white-space:nowrap">frame:newParserValue{ text = text }</code>
 
<!--T:629-->
Returns an object with one method, <code>object:expand()</code>, that returns the result of <code style="white-space:nowrap">[[#frame:preprocess|frame:preprocess]]( text )</code>.
 
==== frame:newTemplateParserValue ==== <!--T:630-->
 
<!--T:631-->
<code style="white-space:nowrap">frame:newTemplateParserValue{ title = title, args = table }</code>
 
<!--T:632-->
: ''Note the use of [[#named arguments|named arguments]].''
 
<!--T:633-->
Returns an object with one method, <code>object:expand()</code>, that returns the result of <code>[[#frame:expandTemplate|frame:expandTemplate]]</code> called with the given arguments.
 
==== frame:argumentPairs ==== <!--T:634-->
 
<!--T:635-->
<code>frame:argumentPairs()</code>
 
<!--T:636-->
Same as <code style="white-space:nowrap">pairs( frame.args )</code>. Included for backwards compatibility.
 
=== HTML library === <!--T:637-->
 
<!--T:638-->
<code>mw.html</code> is a fluent interface for building complex HTML from Lua. A mw.html object can be created using [[#mw.html.create|<code>mw.html.create</code>]].
 
<!--T:639-->
Functions documented as <code>mw.html.name</code> are available on the global <code>mw.html</code> table; functions documented as <code>mw.html:name</code> are methods of an mw.html object (see [[#mw.html.create|<code>mw.html.create</code>]]).
 
<!--T:640-->
A basic example could look like this:
<source lang="lua">
Line 1,749 ⟶ 2,238:
</source>
 
==== mw.html.create ==== <!--T:641-->
<code style="white-space:nowrap">mw.html.create( tagName, args )</code><br>
 
<!--T:642-->
Creates a new mw.html object containing a <code>tagName</code> html element. You can also pass an empty string or nil as <code>tagName</code> in order to create an empty mw.html object.
 
<!--T:643-->
<code>args</code> can be a table with the following keys:
* <code>args.selfClosing</code>: Force the current tag to be self-closing, even if mw.html doesn't recognize it as self-closing
* <code>args.parent</code>: Parent of the current mw.html instance (intended for internal usage)
 
==== mw.html:node ==== <!--T:644-->
<code style="white-space:nowrap">html:node( builder )</code><br>
 
<!--T:645-->
Appends a child mw.html (<code>builder</code>) node to the current mw.html instance. If a nil parameter is passed, this is a no-op.
 
==== mw.html:wikitext ==== <!--T:646-->
<code style="white-space:nowrap">html:wikitext( ... )</code><br>
 
<!--T:647-->
Appends an undetermined number of wikitext strings to the mw.html object.
 
<!--T:648-->
Note that this stops at the first ''nil'' item.
 
==== mw.html:newline ==== <!--T:649-->
<code style="white-space:nowrap">html:newline()</code><br>
 
<!--T:650-->
Appends a newline to the mw.html object.
 
==== mw.html:tag ==== <!--T:651-->
<code style="white-space:nowrap">html:tag( tagName, args )</code><br>
 
<!--T:652-->
Appends a new child node with the given <code>tagName</code> to the builder, and returns a mw.html instance representing that new node. The <code>args</code> parameter is identical to that of [[#mw.html.create|<code>mw.html.create</code>]]
 
==== mw.html:attr ==== <!--T:653-->
<code style="white-space:nowrap">html:attr( name, value )</code><br>
<code style="white-space:nowrap">html:attr( table )</code>
 
<!--T:654-->
Set an HTML attribute with the given <code>name</code> and <code>value</code> on the node. Alternatively a table holding name->value pairs of attributes to set can be passed. In the first form, a value of nil causes any attribute with the given name to be unset if it was previously set.
 
==== mw.html:getAttr ==== <!--T:655-->
<code style="white-space:nowrap">html:getAttr( name )</code><br>
 
<!--T:656-->
Get the value of a html attribute previously set using [[#mw.html:attr|<code>html:attr()</code>]] with the given <code>name</code>.
 
==== mw.html:addClass ==== <!--T:657-->
<code style="white-space:nowrap">html:addClass( class )</code><br>
 
<!--T:658-->
Adds a class name to the node's class attribute. If a nil parameter is passed, this is a no-op.
 
==== mw.html:css ==== <!--T:659-->
<code style="white-space:nowrap">html:css( name, value )</code><br>
<code style="white-space:nowrap">html:css( table )</code>
 
<!--T:660-->
Set a CSS property with the given <code>name</code> and <code>value</code> on the node. Alternatively a table holding name->value pairs of properties to set can be passed. In the first form, a value of nil causes any property with the given name to be unset if it was previously set.
 
==== mw.html:cssText ==== <!--T:661-->
<code style="white-space:nowrap">html:cssText( css )</code><br>
 
<!--T:662-->
Add some raw <code>css</code> to the node's style attribute. If a nil parameter is passed, this is a no-op.
 
==== mw.html:done ==== <!--T:663-->
<code style="white-space:nowrap">html:done()</code><br>
 
<!--T:664-->
Returns the parent node under which the current node was created. Like jQuery.end, this is a convenience function to allow the construction of several child nodes to be chained together into a single statement.
 
==== mw.html:allDone ==== <!--T:665-->
<code style="white-space:nowrap">html:allDone()</code><br>
 
<!--T:666-->
Like [[#mw.html:done|<code>html:done()</code>]], but traverses all the way to the root node of the tree and returns it.
 
=== Language library === <!--T:667-->
 
<!--T:668-->
Language codes are described at [[Language code]]. Many of MediaWiki's language codes are similar to [[:en:IETF language tag|IETF language tags]], but not all MediaWiki language codes are valid IETF tags or vice versa.
 
<!--T:669-->
Functions documented as <code>mw.language.<var>name</var></code> are available on the global <code>mw.language</code> table; functions documented as <code>mw.language:<var>name</var></code> are methods of a language object (see [[#mw.language.new|<code>mw.language.new</code>]]).
 
==== mw.language.fetchLanguageName ==== <!--T:670-->
 
<!--T:671-->
<code style="white-space:nowrap">mw.language.fetchLanguageName( code, inLanguage )</code>
 
<!--T:672-->
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 <code>inLanguage</code>.
 
==== mw.language.fetchLanguageNames ==== <!--T:673-->
 
<!--T:674-->
<code style="white-space:nowrap">mw.language.fetchLanguageNames()</code><br>
<code style="white-space:nowrap">mw.language.fetchLanguageNames( inLanguage )</code><br>
<code style="white-space:nowrap">mw.language.fetchLanguageNames( inLanguage, include )</code><br>
 
<!--T:675-->
Fetch the list of languages known to MediaWiki, returning a table mapping language code to language name.
 
<!--T:676-->
By default the name returned is the language autonym; passing a language code for <code>inLanguage</code> returns all names in that language.
 
<!--T:677-->
By default, only language names known to MediaWiki are returned; passing <code>'all'</code> for <code>include</code> will return all available languages (e.g. from [[Extension:CLDR]]), while passing <code>'mwfile'</code> will include only languages having customized messages included with MediaWiki core or enabled extensions. To explicitly select the default, <code>'mw'</code> may be passed.
 
==== mw.language.getContentLanguage ==== <!--T:678-->
 
<!--T:679-->
<code>mw.language.getContentLanguage()</code><br>
<code>mw.getContentLanguage()</code>
 
<!--T:680-->
Returns a new language object for the wiki's default content language.
 
==== mw.language.getFallbacksFor ==== <!--T:681-->
 
<!--T:682-->
<code style="white-space:nowrap">mw.language.getFallbacksFor( code )</code>
 
<!--T:683-->
Returns a list of MediaWiki's fallback language codes for the specified code.
 
==== mw.language.isKnownLanguageTag ==== <!--T:684-->
 
<!--T:685-->
<code style="white-space:nowrap">mw.language.isKnownLanguageTag( code )</code>
 
<!--T:686-->
Returns true if a language code is known to MediaWiki.
 
<!--T:687-->
A language code is "known" if it is a "valid built-in code" (i.e. it returns true for [[#mw.language.isValidBuiltInCode|<code>mw.language.isValidBuiltInCode</code>]]) and returns a non-empty string for [[#mw.language.fetchLanguageName|<code>mw.language.fetchLanguageName</code>]].
 
==== mw.language.isSupportedLanguage ==== <!--T:688-->
 
<!--T:689-->
<code style="white-space:nowrap">mw.language.isSupportedLanguage( code )</code>
 
<!--T:690-->
Checks whether any localisation is available for that language code in MediaWiki.
 
<!--T:691-->
A language code is "supported" if it is a "valid" code (returns true for [[#mw.language.isValidCode|<code>mw.language.isValidCode</code>]]), contains no uppercase letters, and has a message file in the currently-running version of MediaWiki.
 
<!--T:692-->
It is possible for a language code to be "supported" but not "known" (i.e. returning true for [[#mw.language.isKnownLanguageTag|<code>mw.language.isKnownLanguageTag</code>]]). Also note that certain codes are "supported" despite [[#mw.language.isValidBuiltInCode|<code>mw.language.isValidBuiltInCode</code>]] returning false.
 
==== mw.language.isValidBuiltInCode ==== <!--T:693-->
 
<!--T:694-->
<code style="white-space:nowrap">mw.language.isValidBuiltInCode( code )</code>
 
<!--T:695-->
Returns true if a language code is of a valid form for the purposes of internal customisation of MediaWiki.
 
<!--T:696-->
The code may not actually correspond to any known language.
 
<!--T:697-->
A language code is a "valid built-in code" if it is a "valid" code (i.e. it returns true for [[#mw.language.isValidCode|<code>mw.language.isValidCode</code>]]); consists of only ASCII letters, numbers, and hyphens; and is at least two characters long.
 
<!--T:698-->
Note that some codes are "supported" (i.e. returning true from [[#mw.language.isSupportedLanguage|<code>mw.language.isSupportedLanguage</code>]]) even though this function returns false.
 
==== mw.language.isValidCode ==== <!--T:699-->
 
<!--T:700-->
<code style="white-space:nowrap">mw.language.isValidCode( code )</code>
 
<!--T:701-->
Returns true if a language code string is of a valid form, whether or not it exists. This includes codes which are used solely for customisation via the MediaWiki namespace.
 
<!--T:702-->
The code may not actually correspond to any known language.
 
<!--T:703-->
A language code is valid if it does not contain certain unsafe characters (colons, single- or double-quotes, slashs, backslashs, angle brackets, ampersands, or ASCII NULs) and is otherwise allowed in a page title.
 
==== mw.language.new ==== <!--T:704-->
 
<!--T:705-->
<code style="white-space:nowrap">mw.language.new( code )</code><br>
<code style="white-space:nowrap">mw.getLanguage( code )</code>
 
<!--T:706-->
Creates a new language object. Language objects do not have any publicly accessible properties, but they do have several methods, which are documented below.
 
<!--T:707-->
There is a limit on the number of distinct language codes that may be used on a page. Exceeding this limit will result in errors.
 
==== mw.language:getCode ==== <!--T:708-->
 
<!--T:709-->
<code style="white-space:nowrap">lang:getCode()</code>
 
<!--T:710-->
Returns the language code for this language object.
 
==== mw.language:getFallbackLanguages ==== <!--T:711-->
 
<!--T:712-->
<code style="white-space:nowrap">lang:getFallbackLanguages()</code>
 
<!--T:713-->
Returns a list of MediaWiki's fallback language codes for this language object. Equivalent to <code style="white-space:nowrap">mw.language.getFallbacksFor( lang:getCode() )</code>.
 
==== mw.language:isRTL ==== <!--T:714-->
 
<!--T:715-->
<code style="white-space:nowrap">lang:isRTL()</code>
 
<!--T:716-->
Returns true if the language is written right-to-left, false if it is written left-to-right.
 
==== mw.language:lc ==== <!--T:717-->
 
<!--T:718-->
<code style="white-space:nowrap">lang:lc( s )</code>
 
<!--T:719-->
Converts the string to lowercase, honoring any special rules for the given language.
 
<!--T:720-->
When the [[#Ustring library|Ustring library]] is loaded, the [[#mw.ustring.lower|mw.ustring.lower()]] function is implemented as a call to <code style="white-space:nowrap">mw.language.getContentLanguage():lc( s )</code>.
 
==== mw.language:lcfirst ==== <!--T:721-->
 
<!--T:722-->
<code style="white-space:nowrap">lang:lcfirst( s )</code>
 
<!--T:723-->
Converts the first character of the string to lowercase, as with [[#mw.language:lc|lang:lc()]].
 
==== mw.language:uc ==== <!--T:724-->
 
<!--T:725-->
<code style="white-space:nowrap">lang:uc( s )</code>
 
<!--T:726-->
Converts the string to uppercase, honoring any special rules for the given language.
 
<!--T:727-->
When the [[#Ustring library|Ustring library]] is loaded, the [[#mw.ustring.upper|mw.ustring.upper()]] function is implemented as a call to <code style="white-space:nowrap">mw.language.getContentLanguage():uc( s )</code>.
 
==== mw.language:ucfirst ==== <!--T:728-->
 
<!--T:729-->
<code style="white-space:nowrap">lang:ucfirst( s )</code>
 
<!--T:730-->
Converts the first character of the string to uppercase, as with [[#mw.language:uc|lang:uc()]].
 
==== mw.language:caseFold ==== <!--T:731-->
 
<!--T:732-->
<code style="white-space:nowrap">lang:caseFold( s )</code>
 
<!--T:733-->
Converts the string to a representation appropriate for case-insensitive comparison. Note that the result may not make any sense when displayed.
 
==== mw.language:formatNum ==== <!--T:734-->
 
<!--T:735-->
<code style="white-space:nowrap">lang:formatNum( n )</code>
 
<!--T:736-->
Formats a number with grouping and decimal separators appropriate for the given language. Given 123456.78, this may produce "123,456.78", "123.456,78", or even something like "١٢٣٬٤٥٦٫٧٨" depending on the language and wiki configuration.
 
==== mw.language:formatDate ==== <!--T:737-->
 
<!--T:738-->
<code style="white-space:nowrap">lang:formatDate( format, timestamp, local )</code>
 
<!--T:739-->
Formats a date according to the given format string. If <code>timestamp</code> is omitted, the default is the current time. The value for <code>local</code> must be a boolean or nil; if true, the time is formatted in the [[Manual:$wgLocaltimezone|wiki's local time]] rather than in UTC.
 
<!--T:740-->
The format string and supported values for <code>timestamp</code> are identical to those for the [[Help:Extension:ParserFunctions#.23time|#time parser function]] from [[Extension:ParserFunctions]]. Note that backslashes may need to be doubled in the Lua string where they wouldn't in wikitext:
 
<!--T:741-->
-- This outputs a newline, where <nowiki>{{#time:\n}}</nowiki> would output a literal "n" ({{#time:\n}})
-- This outputs a newline, where <nowiki>{{#time:\n}}</nowiki> would output a literal "n" ({{#time:\n}})
lang:formatDate( '\n' )
Line 1,980 ⟶ 2,538:
lang:formatDate( '\\\\n' )
 
==== mw.language:formatDuration ==== <!--T:742-->
 
<!--T:743-->
<code style="white-space:nowrap">lang:formatDuration( seconds )</code><br>
<code style="white-space:nowrap">lang:formatDuration( seconds, allowedIntervals )</code>
 
<!--T:744-->
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.
 
<!--T:745-->
<code>allowedIntervals</code>, if given, is a table with values naming the interval units to use in the response. These include 'millennia', 'centuries', 'decades', 'years', 'weeks', 'days', 'hours', 'minutes', and 'seconds'.
 
==== mw.language:parseFormattedNumber ==== <!--T:746-->
 
<!--T:747-->
<code style="white-space:nowrap">lang:parseFormattedNumber( s )</code>
 
<!--T:748-->
This takes a number as formatted by [[#mw.language:formatNum|lang:formatNum()]] and returns the actual number. In other words, this is basically a language-aware version of [[#tonumber|<code>tonumber()</code>]].
 
==== mw.language:convertPlural ==== <!--T:749-->
 
<!--T:750-->
{{Anchor|mw.language:plural}}
<code style="white-space:nowrap">lang:convertPlural( n, ... )</code><br>
Line 2,003 ⟶ 2,567:
<code style="white-space:nowrap">lang:plural( n, forms )</code>
 
<!--T:751-->
This chooses the appropriate grammatical form from <code>forms</code> (which must be a [[#sequence|sequence]] table) or <code>...</code> based on the number <code>n</code>. For example, in English you might use <code style="white-space:nowrap">n .. ' ' .. lang:plural( n, 'sock', 'socks' )</code> or <code style="white-space:nowrap">n .. ' ' .. lang:plural( n, { 'sock', 'socks' } )</code> to generate grammatically-correct text whether there is only 1 sock or 200 socks.
 
<!--T:752-->
The necessary values for the sequence are language-dependent, see [[Help:Magic words#Localization]] and [[translatewiki:FAQ#PLURAL]] for some details.
 
==== mw.language:convertGrammar ==== <!--T:753-->
 
<!--T:754-->
{{Anchor|mw.language:grammar}}
<code style="white-space:nowrap">lang:convertGrammar( word, case )</code><br>
<code style="white-space:nowrap">lang:grammar( case, word )</code>
 
<!--T:755-->
: ''Note the different parameter order between the two aliases. <code>convertGrammar</code> matches the order of the method of the same name on MediaWiki's Language object, while <code>grammar</code> matches the order of the parser function of the same name, documented at [[Help:Magic words#Localisation]].''
 
<!--T:756-->
This chooses the appropriate inflected form of <code>word</code> for the given inflection code <code>case</code>.
 
<!--T:757-->
The possible values for <code>word</code> and <code>case</code> are language-dependent, see [[Help:Magic words#Language-dependent word conversions]] and [[translatewiki:Grammar]] for some details.
 
==== mw.language:gender ==== <!--T:758-->
 
<!--T:759-->
<code style="white-space:nowrap">lang:gender( what, masculine, feminine, neutral )</code><br>
<code style="white-space:nowrap">lang:gender( what, { masculine, feminine, neutral } )</code>
 
<!--T:760-->
Chooses the string corresponding to the gender of <code>what</code>, which may be "male", "female", or a registered user name.
 
==== mw.language:getArrow ==== <!--T:761-->
 
<!--T:762-->
<code style="white-space:nowrap">lang:getArrow( direction )</code>
 
<!--T:763-->
Returns a Unicode arrow character corresponding to <code>direction</code>:
* '''forwards''': Either "→" or "←" depending on the directionality of the language.
Line 2,038 ⟶ 2,612:
* '''down''': "↓"
 
==== mw.language:getDir ==== <!--T:764-->
 
<!--T:765-->
<code style="white-space:nowrap">lang:getDir()</code>
 
<!--T:766-->
Returns "ltr" or "rtl", depending on the directionality of the language.
 
==== mw.language:getDirMark ==== <!--T:767-->
 
<!--T:768-->
<code style="white-space:nowrap">lang:getDirMark( opposite )</code>
 
<!--T:769-->
Returns a string containing either U+200E (the left-to-right mark) or U+200F (the right-to-left mark), depending on the directionality of the language and whether <code>opposite</code> is a true or false value.
 
==== mw.language:getDirMarkEntity ==== <!--T:770-->
 
<!--T:771-->
<code style="white-space:nowrap">lang:getDirMarkEntity( opposite )</code>
 
<!--T:772-->
Returns "&amp;lrm;" or "&amp;rlm;", depending on the directionality of the language and whether <code>opposite</code> is a true or false value.
 
==== mw.language:getDurationIntervals ==== <!--T:773-->
 
<!--T:774-->
<code style="white-space:nowrap">lang:getDurationIntervals( seconds )</code><br>
<code style="white-space:nowrap">lang:getDurationIntervals( seconds, allowedIntervals )</code>
 
<!--T:775-->
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.
 
<!--T:776-->
<code>allowedIntervals</code>, if given, is a table with values naming the interval units to use in the response. These include 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', and 'seconds'.
 
=== Message library === <!--T:777-->
 
<!--T:778-->
This library is an interface to the localisation messages and the MediaWiki: namespace.
 
<!--T:779-->
Functions documented as <code>mw.message.name</code> are available on the global <code>mw.message</code> table; functions documented as <code>mw.message:name</code> are methods of a message object (see [[#mw.message.new|<code>mw.message.new</code>]]).
 
==== mw.message.new ==== <!--T:780-->
 
<!--T:781-->
<code style="white-space:nowrap">mw.message.new( key, ... )</code>
 
<!--T:782-->
Creates a new message object for the given message <code>key</code>.
 
<!--T:783-->
The message object has no properties, but has several methods documented below.
 
==== mw.message.newFallbackSequence ==== <!--T:784-->
 
<!--T:785-->
<code style="white-space:nowrap">mw.message.newFallbackSequence( ... )</code>
 
<!--T:786-->
Creates a new message object for the given messages (the first one that exists will be used).
 
<!--T:787-->
The message object has no properties, but has several methods documented below.
 
==== mw.message.newRawMessage ==== <!--T:788-->
 
<!--T:789-->
<code style="white-space:nowrap">mw.message.newRawMessage( msg, ... )</code>
 
<!--T:790-->
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 <code>[[#mw.message:params|params()]]</code> method.
 
<!--T:791-->
The message object has no properties, but has several methods documented below.
 
==== mw.message.rawParam ==== <!--T:792-->
 
<!--T:793-->
<code style="white-space:nowrap">mw.message.rawParam( value )</code>
 
<!--T:794-->
Wraps the value so that it will not be parsed as wikitext by <code>[[#mw.message:parse|msg:parse()]]</code>.
 
==== mw.message.numParam ==== <!--T:795-->
 
<!--T:796-->
<code style="white-space:nowrap">mw.message.numParam( value )</code>
 
<!--T:797-->
Wraps the value so that it will automatically be formatted as by <code>[[#mw.language:formatNum|lang:formatNum()]]</code>. Note this does not depend on the [[#Language library|Language library]] actually being available.
 
==== mw.message.getDefaultLanguage ==== <!--T:798-->
 
<!--T:799-->
<code style="white-space:nowrap">mw.message.getDefaultLanguage()</code>
 
<!--T:800-->
Returns a Language object for the default language.
 
==== mw.message:params ==== <!--T:801-->
 
<!--T:802-->
<code style="white-space:nowrap">msg:params( ... )</code><br>
<code style="white-space:nowrap">msg:params( params )</code>
 
<!--T:803-->
Add parameters to the message, which may be passed as individual arguments or as a [[#sequence|sequence]] table. Parameters must be numbers, strings, or the special values returned by [[#mw.message.numParam|mw.message.numParam()]] or [[#mw.message.rawParam|mw.message.rawParam()]]. If a sequence table is used, parameters must be directly present in the table; references using the [[#Metatables|__index metamethod]] will not work.
 
<!--T:804-->
Returns the <code>msg</code> object, to allow for call chaining.
 
==== mw.message:rawParams ==== <!--T:805-->
 
<!--T:806-->
<code style="white-space:nowrap">msg:rawParams( ... )</code><br>
<code style="white-space:nowrap">msg:rawParams( params )</code>
 
<!--T:807-->
Like [[#mw.message:params|:params()]], but has the effect of passing all the parameters through [[#mw.message.rawParam|mw.message.rawParam()]] first.
 
<!--T:808-->
Returns the <code>msg</code> object, to allow for call chaining.
 
==== mw.message:numParams ==== <!--T:809-->
 
<!--T:810-->
<code style="white-space:nowrap">msg:numParams( ... )</code><br>
<code style="white-space:nowrap">msg:numParams( params )</code>
 
<!--T:811-->
Like [[#mw.message:params|:params()]], but has the effect of passing all the parameters through [[#mw.message.numParam|mw.message.numParam()]] first.
 
<!--T:812-->
Returns the <code>msg</code> object, to allow for call chaining.
 
==== mw.message:inLanguage ==== <!--T:813-->
 
<!--T:814-->
<code style="white-space:nowrap">msg:inLanguage( lang )</code>
 
<!--T:815-->
Specifies the language to use when processing the message. <code>lang</code> may be a string or a table with a <code>getCode()</code> method (i.e. a [[#Language library|Language object]]).
 
<!--T:816-->
The default language is the one returned by <code>[[#mw.message.getDefaultLanguage|mw.message.getDefaultLanguage()]]</code>.
 
<!--T:817-->
Returns the <code>msg</code> object, to allow for call chaining.
 
==== mw.message:useDatabase ==== <!--T:818-->
 
<!--T:819-->
<code style="white-space:nowrap">msg:useDatabase( bool )</code>
 
<!--T:820-->
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.
 
<!--T:821-->
The default is true.
 
<!--T:822-->
Returns the <code>msg</code> object, to allow for call chaining.
 
==== mw.message:plain ==== <!--T:823-->
 
<!--T:824-->
<code style="white-space:nowrap">msg:plain()</code>
 
<!--T:825-->
Substitutes the parameters and returns the message wikitext as-is. Template calls and parser functions are intact.
 
==== mw.message:exists ==== <!--T:826-->
 
<!--T:827-->
<code style="white-space:nowrap">msg:exists()</code>
 
<!--T:828-->
Returns a boolean indicating whether the message key exists.
 
==== mw.message:isBlank ==== <!--T:829-->
 
<!--T:830-->
<code style="white-space:nowrap">msg:isBlank()</code>
 
<!--T:831-->
Returns a boolean indicating whether the message key has content. Returns true if the message key does not exist or the message is the empty string.
 
==== mw.message:isDisabled ==== <!--T:832-->
 
<!--T:833-->
<code style="white-space:nowrap">msg:isDisabled()</code>
 
<!--T:834-->
Returns a boolean indicating whether the message key is disabled. Returns true if the message key does not exist or if the message is the empty string or the string "-".
 
=== Site library === <!--T:835-->
 
==== mw.site.currentVersion ==== <!--T:836-->
 
<!--T:837-->
A string holding the current version of MediaWiki.
 
==== mw.site.scriptPath ==== <!--T:838-->
 
<!--T:839-->
The value of [[Manual:$wgScriptPath|$wgScriptPath]].
 
==== mw.site.server ==== <!--T:840-->
 
<!--T:841-->
The value of [[Manual:$wgServer|$wgServer]].
 
==== mw.site.siteName ==== <!--T:842-->
 
<!--T:843-->
The value of [[Manual:$wgSitename|$wgSitename]].
 
==== mw.site.stylePath ==== <!--T:844-->
 
<!--T:845-->
The value of [[Manual:$wgStylePath|$wgStylePath]].
 
==== mw.site.namespaces ==== <!--T:846-->
 
<!--T:847-->
Table holding data for all namespaces, indexed by number.
 
<!--T:848-->
The data available is:
* '''id''': Namespace number.
Line 2,229 ⟶ 2,861:
* '''associated''': Reference to the associated namespace's data.
 
<!--T:849-->
A metatable is also set that allows for looking up namespaces by name (localized or canonical). For example, both <code>mw.site.namespaces[4]</code> and <code>mw.site.namespaces.Project</code> will return information about the Project namespace.
 
==== mw.site.contentNamespaces ==== <!--T:850-->
 
<!--T:851-->
Table holding just the content namespaces, indexed by number. See [[#mw.site.namespaces|mw.site.namespaces]] for details.
 
==== mw.site.subjectNamespaces ==== <!--T:852-->
 
<!--T:853-->
Table holding just the subject namespaces, indexed by number. See [[#mw.site.namespaces|mw.site.namespaces]] for details.
 
==== mw.site.talkNamespaces ==== <!--T:854-->
 
<!--T:855-->
Table holding just the talk namespaces, indexed by number. See [[#mw.site.namespaces|mw.site.namespaces]] for details.
 
==== mw.site.stats ==== <!--T:856-->
 
<!--T:857-->
Table holding site statistics. Available statistics are:
 
<!--T:858-->
* '''pages''': Number of pages in the wiki.
* '''articles''': Number of articles in the wiki.
Line 2,256 ⟶ 2,894:
* '''admins''': Number of users in group 'sysop' in the wiki.
 
==== mw.site.stats.pagesInCategory ==== <!--T:859-->
 
<!--T:860-->
<code style="white-space:nowrap">mw.site.stats.pagesInCategory( category, which )</code>
 
<!--T:861-->
: {{red|This function is [[Manual:$wgExpensiveParserFunctionLimit|expensive]]}}
 
<!--T:862-->
Gets statistics about the category. If <code>which</code> is unspecified, nil, or "*", returns a table with the following properties:
* '''all''': Total pages, files, and subcategories.
Line 2,268 ⟶ 2,909:
* '''pages''': Number of pages.
 
<!--T:863-->
If <code>which</code> is one of the above keys, just the corresponding value is returned instead.
 
<!--T:864-->
Each new category queried will increment the expensive function count.
 
==== mw.site.stats.pagesInNamespace ==== <!--T:865-->
 
<!--T:866-->
<code style="white-space:nowrap">mw.site.stats.pagesInNamespace( ns )</code>
 
<!--T:867-->
Returns the number of pages in the given namespace (specify by number).
 
==== mw.site.stats.usersInGroup ==== <!--T:868-->
 
<!--T:869-->
<code style="white-space:nowrap">mw.site.stats.usersInGroup( group )</code>
 
<!--T:870-->
Returns the number of users in the given group.
 
==== mw.site.interwikiMap ==== <!--T:871-->
 
<!--T:872-->
<code style="white-space:nowrap">mw.site.interwikiMap( filter )</code>
 
<!--T:873-->
Returns a table holding data about available [[Manual:Interwiki|interwiki]] prefixes. If <code>filter</code> is the string "local", then only data for local interwiki prefixes is returned. If <code>filter</code> is the string "!local", then only data for non-local prefixes is returned. If no filter is specified, data for all prefixes is returned. A "local" prefix in this context is one that is for the same project. For example, on the English Wikipedia, other-language Wikipedias are considered local, while Wiktionary and such are not.
 
<!--T:874-->
Keys in the table returned by this function are interwiki prefixes, and the values are subtables with the following properties:
* '''prefix''' - the interwiki prefix.
Line 2,301 ⟶ 2,951:
* '''tooltip''' - for links listed in $wgExtraInterlanguageLinkPrefixes, this is the tooltip text shown when users hover over the interlanguage link. Nil if not specified.
 
=== Text library === <!--T:875-->
 
<!--T:876-->
The text library provides some common text processing functions missing from the [[#String library|String library]] and the [[#Ustring library|Ustring library]]. These functions are safe for use with UTF-8 strings.
 
==== mw.text.decode ==== <!--T:877-->
 
<!--T:878-->
<code style="white-space:nowrap">mw.text.decode( s )</code><br>
<code style="white-space:nowrap">mw.text.decode( s, decodeNamedEntities )</code>
 
<!--T:879-->
Replaces [[:en:HTML entities|HTML entities]] in the string with the corresponding characters.
 
<!--T:880-->
If <code>decodeNamedEntities</code> is omitted or false, the only named entities recognized are '&amp;lt;', '&amp;gt;', '&amp;amp;', '&amp;quot;', and '&amp;nbsp;'. Otherwise, the list of HTML5 named entities to recognize is loaded from PHP's [http://www.php.net/get_html_translation_table <code>get_html_translation_table</code>] function.
 
==== mw.text.encode ==== <!--T:881-->
 
<!--T:882-->
<code style="white-space:nowrap">mw.text.encode( s )</code><br>
<code style="white-space:nowrap">mw.text.encode( s, charset )</code>
 
<!--T:883-->
Replaces characters in a string with [[:en:HTML entities|HTML entities]]. Characters '<', '>', '&', '"', and the non-breaking space are replaced with the appropriate named entities; all others are replaced with numeric entities.
 
<!--T:884-->
If <code>charset</code> is supplied, it should be a string as appropriate to go inside brackets in a [[#Ustring patterns|Ustring pattern]], i.e. the "set" in <code>[set]</code>. The default charset is <code>'<>&"\'&nbsp;'</code> (the space at the end is the non-breaking space, U+00A0).
 
==== mw.text.jsonDecode ==== <!--T:885-->
 
<!--T:886-->
<code style="white-space:nowrap">mw.text.jsonDecode( s )</code><br>
<code style="white-space:nowrap">mw.text.jsonDecode( s, flags )</code>
 
<!--T:887-->
Decodes a JSON string. <code>flags</code> is 0 or a combination (use <code>+</code>) of the flags <code>mw.text.JSON_PRESERVE_KEYS</code> and <code>mw.text.JSON_TRY_FIXING</code>.
 
<!--T:888-->
Normally JSON's zero-based arrays are renumbered to Lua one-based sequence tables; to prevent this, pass <code>mw.text.JSON_PRESERVE_KEYS</code>.
 
<!--T:889-->
To relax certain requirements in JSON, such as no terminal comma in arrays or objects, pass <code>mw.text.JSON_TRY_FIXING</code>. This is not recommended.
 
<!--T:890-->
Limitations:
* Decoded JSON arrays may not be Lua sequences if the array contains null values.
Line 2,340 ⟶ 3,002:
* 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 <code>mw.text.JSON_PRESERVE_KEYS</code> is used.
 
==== mw.text.jsonEncode ==== <!--T:891-->
 
<!--T:892-->
<code style="white-space:nowrap">mw.text.jsonEncode( value )</code><br>
<code style="white-space:nowrap">mw.text.jsonEncode( value, flags )</code>
 
<!--T:893-->
Encode a JSON string. Errors are raised if the passed value cannot be encoded in JSON. <code>flags</code> is 0 or a combination (use <code>+</code>) of the flags <code>mw.text.JSON_PRESERVE_KEYS</code> and <code>mw.text.JSON_PRETTY</code>.
 
<!--T:894-->
Normally Lua one-based sequence tables are encoded as JSON zero-based arrays; when <code>mw.text.JSON_PRESERVE_KEYS</code> is set in <code>flags</code>, zero-based sequence tables are encoded as JSON arrays.
 
<!--T:895-->
Limitations:
* Empty tables are always encoded as empty arrays (<code>[]</code>), not empty objects (<code>{}</code>).
Line 2,356 ⟶ 3,022:
* When both a number and the string representation of that number are used as keys in the same table, behavior is unspecified.
 
==== mw.text.killMarkers ==== <!--T:896-->
 
<!--T:897-->
<code style="white-space:nowrap">mw.text.killMarkers( s )</code>
 
<!--T:898-->
Removes all MediaWiki [[strip marker]]s from a string.
 
==== mw.text.listToText ==== <!--T:899-->
 
<!--T:900-->
<code style="white-space:nowrap">mw.text.listToText( list )</code><br>
<code style="white-space:nowrap">mw.text.listToText( list, separator, conjunction )</code>
 
<!--T:901-->
Join a list, prose-style. In other words, it's like <code>[[#table.concat|table.concat()]]</code> but with a different separator before the final item.
 
<!--T:902-->
The default separator is taken from [[MediaWiki:comma-separator]] in the wiki's content language, and the default conjuction is [[MediaWiki:and]] concatenated with [[MediaWiki:word-separator]].
 
<!--T:903-->
Examples, using the default values for the messages:
 
<!--T:904-->
-- Returns the empty string
-- Returns the empty string
mw.text.listToText( {} )
Line 2,388 ⟶ 3,061:
mw.text.listToText( { 1, 2, 3, 4, 5 }, '; ', ' or ' )
 
==== mw.text.nowiki ==== <!--T:905-->
 
<!--T:906-->
<code style="white-space:nowrap">mw.text.nowiki( s )</code>
 
<!--T:907-->
Replaces various characters in the string with [[:en:HTML entities|HTML entities]] to prevent their interpretation as wikitext. This includes:
* The following characters: '"', '&', "'", '<', '=', '>', '[', ']', '{', '|', '}'
Line 2,401 ⟶ 3,076:
* A whitespace character following "ISBN", "RFC", or "PMID" will be escaped
 
==== mw.text.split ==== <!--T:908-->
 
<!--T:909-->
<code style="white-space:nowrap">mw.text.split( s, pattern, plain )</code>
 
<!--T:910-->
Splits the string into substrings at boundaries matching the [[#Ustring patterns|Ustring pattern]] <code>pattern</code>. If <code>plain</code> is specified and true, <code>pattern</code> will be interpreted as a literal string rather than as a Lua pattern (just as with the parameter of the same name for <code>[[#mw.ustring.find|mw.ustring.find()]]</code>). Returns a table containing the substrings.
 
<!--T:911-->
For example, <code style="white-space:nowrap">mw.text.split( 'a b\tc\nd', '%s' )</code> would return a table <code style="white-space:nowrap">{ 'a', 'b', 'c', 'd' }</code>.
 
<!--T:912-->
If <code>pattern</code> matches the empty string, <code>s</code> will be split into individual characters.
 
==== mw.text.gsplit ==== <!--T:913-->
 
<!--T:914-->
<code style="white-space:nowrap">mw.text.gsplit( s, pattern, plain )</code>
 
<!--T:915-->
Returns an [[#iterators|iterator function]] that will iterate over the substrings that would be returned by the equivalent call to <code>[[#mw.text.split|mw.text.split()]]</code>.
 
==== mw.text.tag ==== <!--T:916-->
 
<!--T:917-->
<code style="white-space:nowrap">mw.text.tag( name, attrs, content )</code><br>
<code style="white-space:nowrap">mw.text.tag{ name = string, attrs = table, content = string|false }</code>
 
<!--T:918-->
: ''Note the use of [[#named arguments|named arguments]].''
 
<!--T:919-->
Generates an HTML-style tag for <code>name</code>.
 
<!--T:920-->
If <code>attrs</code> is given, it must be a table with string keys. String and number values are used as the value of the attribute; boolean true results in the key being output as an HTML5 valueless parameter; boolean false skips the key entirely; and anything else is an error.
 
<!--T:921-->
If <code>content</code> is not given (or is nil), only the opening tag is returned. If <code>content</code> is boolean false, a self-closed tag is returned. Otherwise it must be a string or number, in which case that content is enclosed in the constructed opening and closing tag. Note the content is not automatically HTML-encoded; use [[#mw.text.encode|mw.text.encode()]] if needed.
 
<!--T:922-->
For properly returning extension tags such as <code><nowiki><ref></nowiki></code>, use [[#frame:extensionTag|frame:extensionTag()]] instead.
 
==== mw.text.trim ==== <!--T:923-->
 
<!--T:924-->
<code style="white-space:nowrap">mw.text.trim( s )</code><br>
<code style="white-space:nowrap">mw.text.trim( s, charset )</code>
 
<!--T:925-->
Remove whitespace or other characters from the beginning and end of a string.
 
<!--T:926-->
If <code>charset</code> is supplied, it should be a string as appropriate to go inside brackets in a [[#Ustring patterns|Ustring pattern]], i.e. the "set" in <code>[set]</code>. The default charset is ASCII whitespace, <code style="white-space:nowrap">"%t%r%n%f "</code>.
 
==== mw.text.truncate ==== <!--T:927-->
 
<!--T:928-->
<code style="white-space:nowrap">mw.text.truncate( text, length )</code><br>
<code style="white-space:nowrap">mw.text.truncate( text, length, ellipsis )</code><br>
<code style="white-space:nowrap">mw.text.truncate( text, length, ellipsis, adjustLength )</code>
 
<!--T:929-->
Truncates <code>text</code> to the specified length, adding <code>ellipsis</code> if truncation was performed. If length is positive, the end of the string will be truncated; if negative, the beginning will be removed. If <code>adjustLength</code> is given and true, the resulting string including ellipsis will not be longer than the specified length.
 
<!--T:930-->
The default value for <code>ellipsis</code> is taken from [[MediaWiki:ellipsis]] in the wiki's content language.
 
<!--T:931-->
Examples, using the default "..." ellipsis:
 
<!--T:932-->
-- Returns "foobarbaz"
mw.text.truncate( "foobarbaz", 9 )
Line 2,468 ⟶ 3,163:
mw.text.truncate( "foobarbaz", 8 )
 
==== mw.text.unstripNoWiki ==== <!--T:933-->
 
<!--T:934-->
<code style="white-space:nowrap">mw.text.unstripNoWiki( s )</code>
 
<!--T:935-->
Replaces MediaWiki &lt;nowiki&gt; [[strip marker]]s with the corresponding text. Other types of strip markers are not changed.
 
==== mw.text.unstrip ==== <!--T:936-->
 
<!--T:937-->
<code style="white-space:nowrap">mw.text.unstrip( s )</code>
 
<!--T:938-->
Equivalent to <code style="white-space:nowrap">mw.text.killMarkers( mw.text.unstripNoWiki( s ) )</code>.
 
<!--T:939-->
This no longer reveals the HTML behind special page transclusion, &lt;ref&gt; tags, and so on as it did in earlier versions of Scribunto.
 
=== Title library === <!--T:940-->
 
==== mw.title.equals ==== <!--T:941-->
 
<!--T:942-->
<code style="white-space:nowrap">mw.title.equals( a, b )</code>
 
<!--T:943-->
Test for whether two titles are equal. Note that fragments are ignored in the comparison.
 
==== mw.title.compare ==== <!--T:944-->
 
<!--T:945-->
<code style="white-space:nowrap">mw.title.compare( a, b )</code>
 
<!--T:946-->
Returns -1, 0, or 1 to indicate whether the title <code>a</code> is less than, equal to, or greater than title <code>b</code>
 
==== mw.title.getCurrentTitle ==== <!--T:947-->
 
<!--T:948-->
<code style="white-space:nowrap">mw.title.getCurrentTitle()</code>
 
<!--T:949-->
Returns the title object for the current page.
 
==== mw.title.new ==== <!--T:950-->
 
<!--T:951-->
<code style="white-space:nowrap">mw.title.new( text, namespace )</code><br>
<code style="white-space:nowrap">mw.title.new( id )</code>
 
<!--T:952-->
: {{red|This function is [[Manual:$wgExpensiveParserFunctionLimit|expensive]] when called with an ID}}
 
<!--T:953-->
Creates a new title object.
 
<!--T:954-->
If a number <code>id</code> is given, an object is created for the title with that page_id. The title referenced will be counted as linked from the current page. If the page_id does not exist, returns nil. The expensive function count will be incremented if the title object created is not for a title that has already been loaded.
 
<!--T:955-->
If a string <code>text</code> 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, <code>namespace</code> (which may be any key found in <code>[[#mw.site.namespaces|mw.site.namespaces]]</code>) will be used. If the text is not a valid title, nil is returned.
 
==== mw.title.makeTitle ==== <!--T:956-->
 
<!--T:957-->
<code style="white-space:nowrap">mw.title.makeTitle( namespace, title, fragment, interwiki )</code>
 
<!--T:958-->
Creates a title object with title <code>title</code> in namespace <code>namespace</code>, optionally with the specified <code>fragment</code> and <code>interwiki</code> prefix. <code>namespace</code> may be any key found in <code>[[#mw.site.namespaces|mw.site.namespaces]]</code>. If the resulting title is not valid, returns nil.
 
<!--T:959-->
Note that <code style="white-space:nowrap">mw.title.new( 'Module:Foo', 'Template' )</code> will create an object for the page Module:Foo, while <code style="white-space:nowrap">mw.title.makeTitle( 'Template', 'Module:Foo' )</code> will create an object for the page Template:Module:Foo.
 
==== Title objects ==== <!--T:960-->
 
<!--T:961-->
A title object has a number of properties and methods. Most of the properties are read-only.
 
<!--T:962-->
Note that fields ending with <code>text</code> return titles as string values whereas the fields ending with <code>title</code> return title objects.
 
<!--T:963-->
* '''id''': The page_id. 0 if the page does not exist. {{red|This [[#Expensive properties|may be expensive]]}}, and the page will be recorded as a link.
* '''interwiki''': The interwiki prefix, or the empty string if none.
Line 2,569 ⟶ 3,286:
* '''getContent()''': Returns the (unparsed) content of the page, or nil if there is no page. The page will be recorded as a transclusion.
 
<!--T:964-->
Title objects may be compared using [[#Relational operators|Relational operators]]. <code style="white-space:nowrap">[[#tostring|tostring]]( title )</code> will return <code>title.prefixedText</code>.
 
===== File metadata ===== <!--T:965-->
Title objects representing a page in the File or Media namespace will have a property called <code>file</code>. {{red|This is [[Manual:$wgExpensiveParserFunctionLimit|expensive]].}} This is a table, structured as follows:
* '''exists''': Whether the file exists. It will be recorded as an image usage. The <code>fileExists</code> property on a Title object exists for backwards compatibility reasons and is an alias for this property. If this is false, all other file properties will be nil.
Line 2,580 ⟶ 3,298:
* '''mimeType''': The [[:en:MIME type|MIME type]] of the file.
 
===== Expensive properties ===== <!--T:966-->
 
<!--T:967-->
The properties id, isRedirect, exists, and contentModel require fetching data about the title from the database. For this reason, the [[Manual:$wgExpensiveParserFunctionLimit|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.
 
<!--T:968-->
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 === <!--T:969-->
 
==== mw.uri.encode ==== <!--T:970-->
 
<!--T:971-->
<code style="white-space:nowrap">mw.uri.encode( s, enctype )</code>
 
<!--T:972-->
[[:en:Percent-encoding|Percent-encodes]] the string. The default type, "QUERY", encodes spaces using '+' for use in query strings; "PATH" encodes spaces as %20; and "WIKI" encodes spaces as '_'.
 
<!--T:973-->
Note that the "WIKI" format is not entirely reversible, as both spaces and underscores are encoded as '_'.
 
==== mw.uri.decode ==== <!--T:974-->
 
<!--T:975-->
<code style="white-space:nowrap">mw.uri.decode( s, enctype )</code>
 
<!--T:976-->
[[:en:Percent-encoding|Percent-decodes]] the string. The default type, "QUERY", decodes '+' to space; "PATH" does not perform any extra decoding; and "WIKI" decodes '_' to space.
 
==== mw.uri.anchorEncode ==== <!--T:977-->
 
<!--T:978-->
<code style="white-space:nowrap">mw.uri.anchorEncode( s )</code>
 
<!--T:979-->
Encodes a string for use in a MediaWiki URI fragment.
 
==== mw.uri.buildQueryString ==== <!--T:980-->
 
<!--T:981-->
<code style="white-space:nowrap">mw.uri.buildQueryString( table )</code>
 
<!--T:982-->
Encodes a table as a URI query string. Keys should be strings; values may be strings or numbers, sequence tables, or boolean false.
 
==== mw.uri.parseQueryString ==== <!--T:983-->
 
<!--T:984-->
<code style="white-space:nowrap">mw.uri.parseQueryString( s, i, j )</code>
 
<!--T:985-->
Decodes the query string <code>s</code> to a table. Keys in the string without values will have a value of false; keys repeated multiple times will have sequence tables as values; and others will have strings as values.
 
<!--T:986-->
The optional numerical arguments <code>i</code> and <code>j</code> can be used to specify a substring of <code>s</code> to be parsed, rather than the entire string. <code>i</code> is the position of the first character of the substring, and defaults to 1. <code>j</code> is the position of the last character of the substring, and defaults to the length of the string. Both <code>i</code> and <code>j</code> can be negative, as in [[#string.sub|string.sub]].
 
==== mw.uri.canonicalUrl ==== <!--T:987-->
 
<!--T:988-->
<code style="white-space:nowrap">mw.uri.canonicalUrl( page, query )</code>
 
<!--T:989-->
Returns a [[#URI object|URI object]] for the canonical URL for a page, with optional query string/table.
 
==== mw.uri.fullUrl ==== <!--T:990-->
 
<!--T:991-->
<code style="white-space:nowrap">mw.uri.fullUrl( page, query )</code>
 
<!--T:992-->
Returns a [[#URI object|URI object]] for the full URL for a page, with optional query string/table.
 
==== mw.uri.localUrl ==== <!--T:993-->
 
<!--T:994-->
<code style="white-space:nowrap">mw.uri.localUrl( page, query )</code>
 
<!--T:995-->
Returns a [[#URI object|URI object]] for the local URL for a page, with optional query string/table.
 
==== mw.uri.new ==== <!--T:996-->
 
<!--T:997-->
<code style="white-space:nowrap">mw.uri.new( s )</code>
 
<!--T:998-->
Constructs a new [[#URI object|URI object]] for the passed string or table. See the description of URI objects for the possible fields for the table.
 
==== mw.uri.validate ==== <!--T:999-->
 
<!--T:1000-->
<code style="white-space:nowrap">mw.uri.validate( table )</code>
 
<!--T:1001-->
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 ==== <!--T:1002-->
 
<!--T:1003-->
The URI object has the following fields, some or all of which may be nil:
 
<!--T:1004-->
* '''protocol''': String protocol/scheme
* '''user''': String user
Line 2,665 ⟶ 3,409:
* '''fragment''': String fragment.
 
<!--T:1005-->
The following properties are also available:
* '''userInfo''': String user and password
Line 2,672 ⟶ 3,417:
* '''relativePath''': String path, query string, and fragment
 
<!--T:1006-->
[[#tostring|<code>tostring()</code>]] will give the URI string.
 
<!--T:1007-->
Methods of the URI object are:
 
===== mw.uri:parse ===== <!--T:1008-->
 
<!--T:1009-->
<code style="white-space:nowrap">uri:parse( s )</code>
 
<!--T:1010-->
Parses a string into the current URI object. Any fields specified in the string will be replaced in the current object; fields not specified will keep their old values.
 
===== mw.uri:clone ===== <!--T:1011-->
 
<!--T:1012-->
<code>uri:clone()</code>
 
<!--T:1013-->
Makes a copy of the URI object.
 
===== mw.uri:extend ===== <!--T:1014-->
 
<!--T:1015-->
<code style="white-space:nowrap">uri:extend( parameters )</code>
 
<!--T:1016-->
Merges the parameters table into the object's query table.
 
=== Ustring library === <!--T:1017-->
 
<!--T:1018-->
The ustring library is intended to be a direct reimplementation of the standard [[#String library|String library]], except that the methods operate on characters in UTF-8 encoded strings rather than bytes.
 
<!--T:1019-->
Most functions will raise an error if the string is not valid UTF-8; exceptions are noted.
 
==== mw.ustring.maxPatternLength ==== <!--T:1020-->
 
<!--T:1021-->
The maximum allowed length of a pattern, in bytes.
 
==== mw.ustring.maxStringLength ==== <!--T:1022-->
 
<!--T:1023-->
The maximum allowed length of a string, in bytes.
 
==== mw.ustring.byte ==== <!--T:1024-->
 
<!--T:1025-->
<code style="white-space:nowrap">mw.ustring.byte( s, i, j )</code>
 
<!--T:1026-->
Returns individual bytes; identical to [[#string.byte|string.byte()]].
 
==== mw.ustring.byteoffset ==== <!--T:1027-->
 
<!--T:1028-->
<code style="white-space:nowrap">mw.ustring.byteoffset( s, l, i )</code>
 
<!--T:1029-->
Returns the byte offset of a character in the string. The default for both <code>l</code> and <code>i</code> is 1. <code>i</code> may be negative, in which case it counts from the end of the string.
 
<!--T:1030-->
The character at <code>l</code> == 1 is the first character starting at or after byte <code>i</code>; the character at <code>l</code> == 0 is the first character starting at or before byte <code>i</code>. Note this may be the same character. Greater or lesser values of <code>l</code> are calculated relative to these.
 
==== mw.ustring.char ==== <!--T:1031-->
 
<!--T:1032-->
<code style="white-space:nowrap">mw.ustring.char( ... )</code>
 
<!--T:1033-->
Much like [[#string.char|string.char()]], except that the integers are Unicode codepoints rather than byte values.
 
==== mw.ustring.codepoint ==== <!--T:1034-->
 
<!--T:1035-->
<code style="white-space:nowrap">mw.ustring.codepoint( s, i, j )</code>
 
<!--T:1036-->
Much like [[#string.byte|string.byte()]], except that the return values are codepoints and the offsets are characters rather than bytes.
 
==== mw.ustring.find ==== <!--T:1037-->
 
<!--T:1038-->
<code style="white-space:nowrap">mw.ustring.find( s, pattern, init, plain )</code>
 
<!--T:1039-->
Much like [[#string.find|string.find()]], except that the pattern is extended as described in [[#Ustring patterns|Ustring patterns]] and the <code>init</code> offset is in characters rather than bytes.
 
==== mw.ustring.format ==== <!--T:1040-->
 
<!--T:1041-->
<code style="white-space:nowrap">mw.ustring.format( format, ... )</code>
 
<!--T:1042-->
Identical to [[#string.format|string.format()]]. Widths and precisions for strings are expressed in bytes, not codepoints.
 
==== mw.ustring.gcodepoint ==== <!--T:1043-->
 
<!--T:1044-->
<code style="white-space:nowrap">mw.ustring.gcodepoint( s, i, j )</code>
 
<!--T:1045-->
Returns three values for iterating over the codepoints in the string. <code>i</code> defaults to 1, and <code>j</code> to -1. This is intended for use in the [[#iterators|iterator form of <code>for</code>]]:
 
<!--T:1046-->
<source lang="lua">
for codepoint in mw.ustring.gcodepoint( s ) do
Line 2,758 ⟶ 3,531:
</source>
 
==== mw.ustring.gmatch ==== <!--T:1047-->
 
<!--T:1048-->
<code style="white-space:nowrap">mw.ustring.gmatch( s, pattern )</code>
 
<!--T:1049-->
Much like [[#string.gmatch|string.gmatch()]], except that the pattern is extended as described in [[#Ustring patterns|Ustring patterns]].
 
==== mw.ustring.gsub ==== <!--T:1050-->
 
<!--T:1051-->
<code style="white-space:nowrap">mw.ustring.gsub( s, pattern, repl, n )</code>
 
<!--T:1052-->
Much like [[#string.gsub|string.gsub()]], except that the pattern is extended as described in [[#Ustring patterns|Ustring patterns]].
 
==== mw.ustring.isutf8 ==== <!--T:1053-->
 
<!--T:1054-->
<code style="white-space:nowrap">mw.ustring.isutf8( s )</code>
 
<!--T:1055-->
Returns true if the string is valid UTF-8, false if not.
 
==== mw.ustring.len ==== <!--T:1056-->
 
<!--T:1057-->
<code style="white-space:nowrap">mw.ustring.len( s )</code>
 
<!--T:1058-->
Returns the length of the string in codepoints, or nil if the string is not valid UTF-8.
 
<!--T:1059-->
See [[#string.len|string.len()]] for a similar function that uses byte length rather than codepoints.
 
==== mw.ustring.lower ==== <!--T:1060-->
 
<!--T:1061-->
<code style="white-space:nowrap">mw.ustring.lower( s )</code>
 
<!--T:1062-->
Much like [[#string.lower|string.lower()]], except that all characters with lowercase to uppercase definitions in Unicode are converted.
 
<!--T:1063-->
If the [[#Language library|Language library]] is also loaded, this will instead call [[#mw.language:lc|lc()]] on the default language object.
 
==== mw.ustring.match ==== <!--T:1064-->
 
<!--T:1065-->
<code style="white-space:nowrap">mw.ustring.match( s, pattern, init )</code>
 
<!--T:1066-->
Much like [[#string.match|string.match()]], except that the pattern is extended as described in [[#Ustring patterns|Ustring patterns]] and the <code>init</code> offset is in characters rather than bytes.
 
==== mw.ustring.rep ==== <!--T:1067-->
 
<!--T:1068-->
<code style="white-space:nowrap">mw.ustring.rep( s, n )</code>
 
<!--T:1069-->
Identical to [[#string.rep|string.rep()]].
 
==== mw.ustring.sub ==== <!--T:1070-->
 
<!--T:1071-->
<code style="white-space:nowrap">mw.ustring.sub( s, i, j )</code>
 
<!--T:1072-->
Much like [[#string.sub|string.sub()]], except that the offsets are characters rather than bytes.
 
==== mw.ustring.toNFC ==== <!--T:1073-->
 
<!--T:1074-->
<code style="white-space:nowrap">mw.ustring.toNFC( s )</code>
 
<!--T:1075-->
Converts the string to [[:en:Normalization Form C|Normalization Form C]]. Returns nil if the string is not valid UTF-8.
 
==== mw.ustring.toNFD ==== <!--T:1076-->
 
<!--T:1077-->
<code style="white-space:nowrap">mw.ustring.toNFD( s )</code>
 
<!--T:1078-->
Converts the string to [[:en:Normalization Form D|Normalization Form D]]. Returns nil if the string is not valid UTF-8.
 
==== mw.ustring.upper ==== <!--T:1079-->
 
<!--T:1080-->
<code style="white-space:nowrap">mw.ustring.upper( s )</code>
 
<!--T:1081-->
Much like [[#string.upper|string.upper()]], except that all characters with uppercase to lowercase definitions in Unicode are converted.
 
<!--T:1082-->
If the [[#Language library|Language library]] is also loaded, this will instead call [[#mw.language:uc|uc()]] on the default language object.
 
==== Ustring patterns ==== <!--T:1083-->
 
<!--T:1084-->
Patterns in the ustring functions use the same syntax as the [[#Patterns|String library patterns]]. The major difference is that the character classes are redefined in terms of [[:en:Unicode character property|Unicode character properties]]:
* '''<code>%a</code>''': represents all characters with General Category "Letter".
Line 2,843 ⟶ 3,642:
* '''<code>%x</code>''': adds fullwidth character versions of the hex digits.
 
<!--T:1085-->
In all cases, characters are interpreted as Unicode characters instead of bytes, so ranges such as <code>[0-9]</code>, patterns such as <code>%b«»</code>, and quantifiers applied to multibyte characters will work correctly. Empty captures will capture the position in code points rather than bytes.
 
== Loadable libraries == <!--T:1086-->
 
<!--T:1087-->
These libraries are not included by default, but if needed may be loaded using <code>[[#require|require()]]</code>.
 
=== bit32 === <!--T:1088-->
 
<!--T:1089-->
This emulation of the Lua 5.2 <code>bit32</code> library may be loaded using
 
<!--T:1090-->
bit32 = require( 'bit32' )
bit32 = require( 'bit32' )
 
<!--T:1091-->
The bit32 library provides [[:en:Bitwise operation|bitwise operations]] on unsigned 32-bit integers. Input numbers are truncated to integers (in an unspecified manner) and reduced modulo 2<sup>32</sup> so the value is in the range 0 to 2<sup>32</sup>−1; return values are also in this range.
 
<!--T:1092-->
When bits are numbered (as in [[#bit32.extract|bit32.extract()]]), 0 is the least-significant bit (the one with value 2<sup>0</sup>) and 31 is the most-significant (the one with value 2<sup>31</sup>).
 
==== bit32.band ==== <!--T:1093-->
 
<!--T:1094-->
<code style="white-space:nowrap">bit32.band( ... )</code>
 
<!--T:1095-->
Returns the [[:en:Bitwise operation#AND|bitwise AND]] of its arguments: the result has a bit set only if that bit is set in all of the arguments.
 
<!--T:1096-->
If given zero arguments, the result has all bits set.
 
==== bit32.bnot ==== <!--T:1097-->
 
<!--T:1098-->
<code style="white-space:nowrap">bit32.bnot( x )</code>
 
<!--T:1099-->
Returns the [[:en:Bitwise operation#NOT|bitwise complement]] of <code>x</code>.
 
==== bit32.bor ==== <!--T:1100-->
 
<!--T:1101-->
<code style="white-space:nowrap">bit32.bor( ... )</code>
 
<!--T:1102-->
Returns the [[:en:Bitwise operation#OR|bitwise OR]] of its arguments: the result has a bit set if that bit is set in any of the arguments.
 
<!--T:1103-->
If given zero arguments, the result has all bits clear.
 
==== bit32.btest ==== <!--T:1104-->
 
<!--T:1105-->
<code style="white-space:nowrap">bit32.btest( ... )</code>
 
<!--T:1106-->
Equivalent to <code style="white-space:nowrap">bit32.band( ... ) ~= 0</code>
 
==== bit32.bxor ==== <!--T:1107-->
 
<!--T:1108-->
<code style="white-space:nowrap">bit32.bxor( ... )</code>
 
<!--T:1109-->
Returns the [[:en:Bitwise operation#XOR|bitwise XOR]] of its arguments: the result has a bit set if that bit is set in an odd number of the arguments.
 
<!--T:1110-->
If given zero arguments, the result has all bits clear.
 
==== bit32.extract ==== <!--T:1111-->
 
<!--T:1112-->
<code style="white-space:nowrap">bit32.extract( n, field, width )</code>
 
<!--T:1113-->
Extracts <code>width</code> bits from <code>n</code>, starting with bit <code>field</code>. Accessing bits outside of the range 0 to 31 is an error.
 
<!--T:1114-->
If not specified, the default for <code>width</code> is 1.
 
==== bit32.replace ==== <!--T:1115-->
 
<!--T:1116-->
<code style="white-space:nowrap">bit32.replace( n, v, field, width )</code>
 
<!--T:1117-->
Replaces <code>width</code> bits in <code>n</code>, starting with bit <code>field</code>, with the low <code>width</code> bits from <code>v</code>. Accessing bits outside of the range 0 to 31 is an error.
 
<!--T:1118-->
If not specified, the default for <code>width</code> is 1.
 
==== bit32.lshift ==== <!--T:1119-->
 
<!--T:1120-->
<code style="white-space:nowrap">bit32.lshift( n, disp )</code>
 
<!--T:1121-->
Returns the number <code>n</code> [[:en:Bitwise operation#Bit shifts|shifted]] <code>disp</code> bits to the left. This is a [[:en:Logical shift|logical shift]]: inserted bits are 0. This is generally equivalent to multiplying by 2<sup><code>disp</code></sup>.
 
<!--T:1122-->
Note that a displacement over 31 will result in 0.
 
==== bit32.rshift ==== <!--T:1123-->
 
<!--T:1124-->
<code style="white-space:nowrap">bit32.rshift( n, disp )</code>
 
<!--T:1125-->
Returns the number <code>n</code> [[:en:Bitwise operation#Bit shifts|shifted]] <code>disp</code> bits to the right. This is a [[:en:Logical shift|logical shift]]: inserted bits are 0. This is generally equivalent to dividing by 2<sup><code>disp</code></sup>.
 
<!--T:1126-->
Note that a displacement over 31 will result in 0.
 
==== bit32.arshift ==== <!--T:1127-->
 
<!--T:1128-->
<code style="white-space:nowrap">bit32.arshift( n, disp )</code>
 
<!--T:1129-->
Returns the number <code>n</code> shifted <code>disp</code> bits to the right. This is an [[:en:Arithmetic shift|arithmetic shift]]: if <code>disp</code> is positive, the inserted bits will be the same as bit 31 in the original number.
 
<!--T:1130-->
Note that a displacement over 31 will result in 0 or 4294967295.
 
==== bit32.lrotate ==== <!--T:1131-->
 
<!--T:1132-->
<code style="white-space:nowrap">bit32.lrotate( n, disp )</code>
 
<!--T:1133-->
Returns the number <code>n</code> [[:en:Bitwise operation#Rotate no carry|rotated]] <code>disp</code> bits to the left.
 
<!--T:1134-->
Note that rotations are equivalent modulo 32: a rotation of 32 is the same as a rotation of 0, 33 is the same as 1, and so on.
 
==== bit32.rrotate ==== <!--T:1135-->
 
<!--T:1136-->
<code style="white-space:nowrap">bit32.rrotate( n, disp )</code>
 
<!--T:1137-->
Returns the number <code>n</code> [[:en:Bitwise operation#Rotate no carry|rotated]] <code>disp</code> bits to the right.
 
<!--T:1138-->
Note that rotations are equivalent modulo 32: a rotation of 32 is the same as a rotation of 0, 33 is the same as 1, and so on.
 
=== libraryUtil === <!--T:1139-->
 
<!--T:1140-->
This library contains methods useful when implementing Scribunto libraries. It may be loaded using
 
<!--T:1141-->
libraryUtil = require( 'libraryUtil' )
libraryUtil = require( 'libraryUtil' )
 
==== libraryUtil.checkType ==== <!--T:1142-->
 
<!--T:1143-->
<code style="white-space:nowrap">libraryUtil.checkType( name, argIdx, arg, expectType, nilOk )</code>
 
<!--T:1144-->
Raises an error if <code style="white-space:nowrap">[[#type|type]]( arg )</code> does not match <code>expectType</code>. In addition, no error will be raised if <code>arg</code> is nil and <code>nilOk</code> is true.
 
<!--T:1145-->
<code>name</code> is the name of the calling function, and <code>argIdx</code> is the position of the argument in the argument list. These are used in formatting the error message.
 
==== libraryUtil.checkTypeMulti ==== <!--T:1146-->
 
<!--T:1147-->
<code style="white-space:nowrap">libraryUtil.checkTypeMulti( name, argIdx, arg, expectTypes )</code>
 
<!--T:1148-->
Raises an error if <code style="white-space:nowrap">[[#type|type]]( arg )</code> does not match any of the strings in the array <code>expectTypes</code>.
 
<!--T:1149-->
This is for arguments that have more than one valid type.
 
==== libraryUtil.checkTypeForIndex ==== <!--T:1150-->
 
<!--T:1151-->
<code style="white-space:nowrap">libraryUtil.checkTypeForIndex( index, value, expectType )</code>
 
<!--T:1152-->
Raises an error if <code style="white-space:nowrap">[[#type|type]]( value )</code> does not match <code>expectType</code>.
 
<!--T:1153-->
This is intended for use in implementing a <code>__newindex</code> [[#Metatables|metamethod]].
 
==== libraryUtil.checkTypeForNamedArg ==== <!--T:1154-->
 
<!--T:1155-->
<code style="white-space:nowrap">libraryUtil.checkTypeForNamedArg( name, argName, arg, expectType, nilOk )</code>
 
<!--T:1156-->
Raises an error if <code style="white-space:nowrap">[[#type|type]]( arg )</code> does not match <code>expectType</code>. In addition, no error will be raised if <code>arg</code> is nil and <code>nilOk</code> is true.
 
<!--T:1157-->
This is intended to be used as an equivalent to <code>[[#libraryUtil.checkType|libraryUtil.checkType()]]</code> in methods called using Lua's "named argument" syntax, <code style="white-space:nowrap">func{ name = value }</code>.
 
==== libraryUtil.makeCheckSelfFunction ==== <!--T:1158-->
 
<!--T:1159-->
<code style="white-space:nowrap">libraryUtil.makeCheckSelfFunction( libraryName, varName, selfObj, selfObjDesc )</code>
 
<!--T:1160-->
This is intended for use in implementing "methods" on object tables that are intended to be called with the <code>obj:method()</code> syntax. It returns a function that should be called at the top of these methods with the <code>self</code> argument and the method name, which will raise an error if that <code>self</code> object is not <code>selfObj</code>.
 
<!--T:1161-->
This function will generally be used in a library's constructor function, something like this:
 
<!--T:1162-->
function myLibrary.new()
function myLibrary.new()
local obj = {}
local checkSelf = libraryUtil.makeCheckSelfFunction( 'myLibrary', 'obj', obj, 'myLibrary object' )
Line 3,012 ⟶ 3,869:
end
 
=== luabit === <!--T:1163-->
 
<!--T:1164-->
The [http://luaforge.net/projects/bit/ luabit] library modules "bit" and "hex" may be loaded using
 
<!--T:1165-->
bit = require( 'luabit.bit' )
bit = require( 'luabit.bit' )
hex = require( 'luabit.hex' )
 
<!--T:1166-->
Note that the [[#bit32|bit32 library]] contains the same operations as "luabit.bit", and the operations in "luabit.hex" may be performed using <code>[[#string.format|string.format()]]</code> and <code>[[#tonumber|tonumber()]]</code>.
 
<!--T:1167-->
The luabit module "noki" is not available, as it is entirely useless in Scribunto. The luabit module "utf8" is also not available, as it was considered redundant to the [[#Ustring library|Ustring library]].
 
=== ustring === <!--T:1168-->
 
<!--T:1169-->
The pure-Lua backend to the [[#Ustring library|Ustring library]] may be loaded using
 
<!--T:1170-->
ustring = require( 'ustring' )
ustring = require( 'ustring' )
 
<!--T:1171-->
In all cases the Ustring library (<code>mw.ustring</code>) should be used instead, as that replaces many of the slower and more memory-intensive operations with callbacks into PHP code.
 
== Extension libraries (mw.ext) == <!--T:1172-->
 
<!--T:1173-->
The following MediaWiki extensions provide additional Scribunto libraries:
 
<!--T:1174-->
*[[Extension:Wikibase Client|Wikibase Client]]&nbsp;– provides access to [[:d:Wikidata:Main Page|Wikidata]]. See [[Extension:WikibaseClient/Lua]].
 
<!--T:1175-->
See also the lists of extensions using the [[:Category:ScribuntoExternalLibraries extensions|ScribuntoExternalLibraries]] and [[:Category:ScribuntoExternalLibraryPaths extensions|ScribuntoExternalLibraryPaths]] hooks.
 
== Planned Scribunto libraries == <!--T:1176-->
 
<!--T:1177-->
These libraries are planned, or are in Gerrit pending review.
 
<!--T:1178-->
: ''(none at this time)''
 
== Differences from standard Lua == <!--T:1179-->
 
=== Changed functions === <!--T:1180-->
The following functions have been '''modified''':
; [http://www.lua.org/manual/5.1/manual.html#pdf-setfenv setfenv()]
Line 3,059 ⟶ 3,928:
; [http://www.lua.org/manual/5.1/manual.html#pdf-require require()]: Can fetch certain built-in modules distributed with Scribunto, as well as modules present in the Module namespace of the wiki. To fetch wiki modules, use the full page name including the namespace. Cannot otherwise access the local filesystem.
 
=== Removed functions and packages === <!--T:1181-->
The following packages are '''mostly removed'''. Only those functions listed are available:
; [http://www.lua.org/manual/5.1/manual.html#5.3 package.*]: Filesystem and C library access has been removed. Available functions and tables are:
Line 3,075 ⟶ 3,944:
 
 
<!--T:1182-->
The following functions and packages are '''not''' available:
; [http://www.lua.org/manual/5.1/manual.html#pdf-collectgarbage collectgarbage()]
Line 3,087 ⟶ 3,957:
; [http://www.lua.org/manual/5.1/manual.html#pdf-string.dump string.dump()]: May expose private data from parent environments.
 
=== Additional caveats === <!--T:1183-->
; Referential data structures: Circular data structures and data structures where the same node may be reached by more than one path cannot be correctly sent to PHP. Attempting to do so will cause undefined behavior. This includes (but is not limited to) returning such data structures from the module called by <code><nowiki>{{#invoke:}}</nowiki></code> and passing such data structures as parameters to Scribunto library functions that are implemented as callbacks into PHP.<p>Such data structures may be used freely within Lua, including as the return values of modules loaded with <code>[[#mw.loadData|mw.loadData()]]</code>.
 
== Writing Scribunto libraries == <!--T:1184-->
 
<!--T:1185-->
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.
 
<!--T:1186-->
A Scribunto library will generally consist of five parts:
* The PHP portion of the library.
Line 3,101 ⟶ 3,973:
* The documentation.
 
<!--T:1187-->
Existing libraries serve as a good example.
 
=== Library === <!--T:1188-->
 
<!--T:1189-->
The PHP portion of the library is a class that must extend <code>Scribunto_LuaLibraryBase</code>. See the documentation for that class for implementation details. In the Scribunto extension, this file should be placed in <code>engines/LuaCommon/''Name''Library.php</code>, and a mapping added to <code>Scribunto_LuaEngine::$libraryClasses</code>. Other extensions should use the <code>ScribuntoExternalLibraries</code> hook. In either case, the key should match the Lua module name ("mw.''name''" for libraries in Scribunto, or "mw.ext.''name''" for extension libraries).
 
<!--T:1190-->
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 <code>engines/LuaCommon/lualib/mw.''name''.lua</code>. This file should generally include boilerplate something like this:
 
<!--T:1191-->
<syntaxhighlight lang=lua>
local object = {}
local php
 
<!--T:1192-->
function object.setupInterface( options )
-- Remove setup function
object.setupInterface = nil
 
<!--T:1193-->
-- Copy the PHP callbacks to a local variable, and remove the global
-- Copy the PHP callbacks to a local variable, and remove the global
php = mw_interface
mw_interface = nil
 
<!--T:1194-->
-- Do any other setup here
 
<!--T:1195-->
-- Install into the mw global
mw = mw or {}
mw.ext = mw.ext or {}
mw.ext.NAME = object
 
<!--T:1196-->
-- Indicate that we're loaded
package.loaded['mw.ext.NAME'] = object
end
 
<!--T:1197-->
return object
</syntaxhighlight>
 
<!--T:1198-->
The module in <code>engines/LuaCommon/lualib/libraryUtil.lua</code> (load this with <code>local util = require 'libraryUtil'</code>) contains some functions that may be helpful.
 
<!--T:1199-->
Be sure to run the Scribunto test cases with your library loaded, even if your library doesn't itself provide any test cases. The standard test cases include tests for things like libraries adding unexpected global variables. Also, if the library is loaded with PHP, any upvalues that its Lua functions have will not be reset between #invoke's. Care must be taken to ensure that modules can't abuse this to transfer information between #invoke's.
 
=== Test cases === <!--T:1200-->
 
<!--T:1201-->
The Scribunto extension includes a base class for test cases, <code>Scribunto_LuaEngineTestBase</code>, which will run the tests against both the LuaSandbox and LuaStandalone engines. The library's test case should extend this class, and should not override <code>static function suite()</code>. In the Scribunto extension, the test case should be in <code>tests/engines/LuaCommon/''Name''LibraryTest.php</code> and added to the array in <code>ScribuntoHooks::unitTestsList()</code> (in <code>common/Hooks.php</code>); extensions should add the test case in their own [[Manual:Hooks/UnitTestsList|<code>UnitTestsList</code> hook]] function, probably conditional on whether <code>$wgAutoloadClasses['Scribunto_LuaEngineTestBase']</code> is set.
 
<!--T:1202-->
Most of the time, all that is needed to make the test case is this:
 
<!--T:1203-->
class ''ClassName''Test extends Scribunto_LuaEngineTestBase {
class ''ClassName''Test extends Scribunto_LuaEngineTestBase {
protected static $moduleName = '<i>ClassName</i>Test';
Line 3,155 ⟶ 4,042:
}
 
<!--T:1204-->
This will load the file <code>''ClassName''Tests.lua</code> as if it were the page "Module:''ClassName''Tests", expecting it to return an object with the following properties:
* '''count''': Integer, number of tests
Line 3,160 ⟶ 4,048:
* '''run( n )''': Function that runs test <code>n</code> and returns one string.
 
<!--T:1205-->
If <code>getTestModules()</code> is declared as shown, "Module:TestFramework" is available which provides many useful helper methods. If this is used, <code>''ClassName''Tests.lua</code> would look something like this:
 
<!--T:1206-->
local testframework = require 'Module:TestFramework'
local testframework = require 'Module:TestFramework'
return testframework.getTestProvider( {
Line 3,168 ⟶ 4,058:
} )
 
<!--T:1207-->
Each test is itself a table, with the following properties:
* '''name''': The name of the test.
Line 3,175 ⟶ 4,066:
* '''type''': Optional "type" of the test, default is "Normal".
 
<!--T:1208-->
The type controls the format of <code>expect</code> and how <code>func</code> is called. Included types are:
* '''Normal''': <code>expect</code> is a table of return values, or a string if the test should raise an error. <code>func</code> is simply called.
Line 3,180 ⟶ 4,072:
* '''ToString''': Like "Normal", except each return value is passed through <code>[[#tostring|tostring()]]</code>.
 
==== Test cases in another extension ==== <!--T:1209-->
 
<!--T:1210-->
There are (at least) two ways to run PHPUnit tests:
# Run phpunit against core, allowing the tests/phpunit/suites/ExtensionsTestSuite.php to find the extension's tests using the [[Manual:Hooks/UnitTestsList|UnitTestsList hook]]. If your extension's test class names all contain a unique component (e.g. the extension's name), the <code>--filter</code> option may be used to run only your extension's tests.
# Run phpunit against the extension directory, where it will pick up any file ending in "Test.php".
 
<!--T:1211-->
Either of these will work fine if Scribunto is loaded in LocalSettings.php. And it is easy for method #1 to work if Scribunto is not loaded, as the UnitTestsList hook can easily be written to avoid returning the Scribunto test when <code>$wgAutoloadClasses['Scribunto_LuaEngineTestBase']</code> is not set.
 
<!--T:1212-->
But [[Jenkins]] uses method #2. For Jenkins to properly run the tests, you will need to add Scribunto as a dependency for your extension. See {{gerrit|56570}} for an example of how this is done.
 
<!--T:1213-->
If for some reason you need the tests to be able to run using method #2 without Scribunto loaded, one workaround is to add this check to the top of your unit test file:
 
<!--T:1214-->
if ( !isset( $GLOBALS['wgAutoloadClasses']['Scribunto_LuaEngineTestBase'] ) ) {
if ( !isset( $GLOBALS['wgAutoloadClasses']['Scribunto_LuaEngineTestBase'] ) ) {
return;
}
 
=== Documentation === <!--T:1215-->
 
<!--T:1216-->
Modules included in Scribunto should include documentation in the [[#Scribunto libraries|Scribunto libraries]] section above. Extension libraries should include documentation in a subpage of their own Extension page, and link to that documentation from [[#Extension libraries (mw.ext)]].
 
==See also== <!--T:1217-->
*[[w:Lua (programming language)]]
 
== License == <!--T:1218-->
 
<!--T:1219-->
This manual is derived from the [http://www.lua.org/manual/5.1/index.html Lua 5.1 reference manual], which is available under the [http://www.lua.org/license.html MIT license].
 
<!--T:1220-->
{{mbox
| type = license
Line 3,213 ⟶ 4,113:
Copyright © 1994–2012 Lua.org, PUC-Rio.
 
<!--T:1221-->
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 
<!--T:1222-->
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
<!--T:1223-->
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
}}
 
<!--T:1224-->
This derivative manual may also be copied under the terms of the same license.
</translate>