Lua reference manual/Scribunto libraries

Scribunto libraries
All Scribunto libraries are located in the table.

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

mw.clearLogBuffer
Removes all data logged with mw.log.

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

mw.executeFunction
This creates a new copy of the frame object, calls the function with that as its parameter, then calls tostring on all results and concatenates them (no separator) and returns the resulting string.

Note this will not work correctly from the debug console, as there is no frame object to copy.

mw.executeModule
Executes the function in a sandboxed environment; the function cannot affect anything in the current environment, with the exception of side effects of calling any existing closures.

The name "executeModule" is because this is the function used when a module is loaded from the Module: namespace.

mw.getCurrentFrame
Returns the current frame object.

mw.getLogBuffer
Returns the data logged by mw.log, as a string.

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

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

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

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

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

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

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

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

then  will return "arg1",   will return "arg2", and   (or  ) will return "arg3". It is also possible to iterate over arguments using  or.

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

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

For performance reasons, frame.args is a metatable, not a real table of arguments. Argument values are requested from MediaWiki on demand. This means that most other table methods will not work correctly, including,  , and the functions in the Table library.

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

frame:getParent
Called on the frame created by, returns the frame for the page that called. Called on that frame, returns nil. This lets you just put  inside a template and the parameters passed to the template (i.e.  ) will be passed straight to the Lua module, without having to include them directly (so, you don't have to do  ).

Example:
 * Module:Hello


 * Template:Hello


 * Article


 * This will output "Hello, Wikia!".

frame:expandTemplate
Note the use of named args syntactic sugar; see Function calls for details.

This is transclusion. The call

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

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

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

-- This is roughtly equivalent to wikitext like --  frame:expandTemplate{ title = 'template', args = { '|' } } -- This is roughtly equivalent to wikitext like --  frame:expandTemplate{ title = 'template', args = { ' | ' } }

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

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

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

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

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

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

frame:argumentPairs
Same as. Included for backwards compatibility.

Language library
Language codes are described at Language code.

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

Difference from MW core:  and   removed, and   has been modified.

mw.language.fetchLanguageName
The full name of the native language name (language autonym).

Difference from MW core: The second parameter,, which returns the language name translated in target language if a value is given for it, is not supported due to missing methods in MW 1.19.

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

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

The code may not actually correspond to any known language.

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

The code may not actually correspond to any known language.

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

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

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

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

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

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

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

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

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

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

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

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

The format string and supported values for  are identical to those for the #time parser function from Extension:ParserFunctions. Note that backslashes may need to be doubled in the Lua string where they wouldn't in wikitext:

-- This outputs a newline, where would output a literal "n" lang:formatDate( '\n' ) -- This outputs a literal "n", where would output a backslash -- followed by the month number. lang:formatDate( '\\n' ) -- This outputs a backslash followed by the month number, where -- would output two backslashes followed by the month number. lang:formatDate( '\\\\n' )

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

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

The necessary values for the sequence are language-dependent, see mw:Help:Magic words and FAQ for some details.

mw.language:convertGrammar

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

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

The possible values for  and   are language-dependent, see mw:Help:Magic words and Grammar for some details.

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

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

mw.site.scriptPath
The value of $wgScriptPath.

mw.site.server
The value of $wgServer.

mw.site.siteName
The value of $wgSitename.

mw.site.stylePath
The value of $wgStylePath.

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

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

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

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

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

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

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


 * pages: Number of pages in the wiki.
 * articles: Number of articles in the wiki.
 * files: Number of files in the wiki.
 * edits: Number of edits in the wiki.
 * views: Number of views in the wiki. Not available if $wgDisableCounters is set.
 * users: Number of users in the wiki.
 * activeUsers: Number of active users in the wiki.
 * admins: Number of users in group 'sysop' in the wiki.

mw.site.stats.pagesInCategory

 * This function is expensive

Gets statistics about the category. If  is unspecified, nil, or "*", returns a table with the following properties:
 * all: Total pages, files, and subcategories.
 * subcats: Number of subcategories.
 * files: Number of files.
 * pages: Number of pages.

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

Each new category queried will increment the expensive function count.

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

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

mw.uri.encode
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 '_'.

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

mw.uri.decode
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
Encodes a string for use in a MediaWiki URI fragment.

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

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

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

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

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

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

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

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


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

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

will give the URI string.

Methods of the URI object are:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

for codepoint in mw.ustring.gcodepoint( s ) do    block end

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

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

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

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

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

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

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

mw.ustring.rep
Identical to string.rep.

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

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

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

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

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

Ustring patterns
Patterns in the ustring functions use the same syntax as the String library patterns. The major difference is that the character classes are redefined in terms of Unicode character properties:
 *  : represents all characters with General Category "Letter".
 *  : represents all characters with General Category "Control".
 *  : represents all characters with General Category "Decimal Number".
 *  : represents all characters with General Category "Lowercase Letter".
 *  : represents all characters with General Category "Punctuation".
 *  : represents all characters with General Category "Separator", plus tab, linefeed, carriage return, vertical tab, and form feed.
 *  : represents all characters with General Category "Uppercase Letter".
 *  : represents all characters with General Category "Letter" or "Decimal Number".
 *  : adds fullwidth character versions of the hex digits.

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

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

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

A basic example could look like this:

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

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

mw.html:node
Appends a child mw.html node to the current mw.html instance.

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

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

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

mw.html:attr
Set an HTML attribute with the given  and   on the node. Alternatively a table holding name->value pairs of attributes to set can be passed.

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

mw.html:addClass
Adds a class name to the node's class attribute.

mw.html:css
Set a CSS property with the given  and   on the node. Alternatively a table holding name->value pairs of properties to set can be passed.

mw.html:cssText
Add some raw  to the node's style attribute.

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

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