User:Gechy/lua-scripting

Overview
Lua is a programming language implemented on Wikipedia with some substantial restrictions via Scribunto. Its purpose is to allow you to process the data which is available on Wikipedia content pages to allow various sorts of customized display of information. Lua is supported as a scripting language in all Wikimedia Foundation sites (since March 2013), via the Scribunto extension. for example. See also [|the tutorial].

The Scribunto (Latin: "they shall write/let them write (in the future)") extension allows for embedding scripting languages in MediaWiki.

Currently the only supported scripting language is Lua.

Why Lua Scripting
Templates and ParserFunctions were introduced to allow end-users of MediaWiki to replicate content easily and build tools using basic logic, effectively turning wikitext into a limited programming language.

This project aims to make it possible for MediaWiki end-users to use a proper scripting language that will be more powerful and efficient than ad-hoc ParserFunctions-based logic.

Initially MediaWiki templates were pieces of wikitext that were substituted into pages instead of copy-pasting. By 2005, any other use was rare and, to some extent, controversial. In 2006, ParserFunctions were enabled, allowing users to use constructions such as  and , essentially turning wikitext into a purely functional programming language (i.e., a language that has no concept of state at any level and one part of the code may not affect any other part, it can only change its own output). This eventually caused several problems, including performance (some pages are overloaded with templates and require 40 seconds or more to parse/render) and readability (just take a look at this).

However, complex templates have caused performance issues and bottlenecks.

Installation and configuration
Scribunto comes bundled with Lua binary distributions for Linux (x86 and x86-64), Mac OS X Lion, and Windows (32- and 64-bit). For detailed explanation see mw:Extension:Scribunto.

Check out the Lua.org demo if you don't want to download Scribunto just yet.

Setting up
The software used by Wikipedia, called MediaWiki, has an extension that provides a version of Lua that can be used within Wikipedia pages. The extension is called Scribunto.

On a MediaWiki wiki with Scribunto enabled, create a page with a title starting with "Module:", for example "Module:Bananas". Into this new page, copy the following text:

Save that, then on another(non-module) page, type:

The "hello" function is exported from the module, and the result of the function is returned.

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.

For hands-on setting-up see Setting up really fast.

Working with modules
The module itself must return a Lua table containing the functions that may be called by. 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.

Any functions that are not added to this table, whether local or global, will not be accessible by, but globals might be accessible from other modules loaded using. It is generally good style for the module to declare all functions and variables local.

Wrap up this session by creating your own lua module

Accessing parameters from wiki
Functions called by  will be passed a single parameter, that being a frame object. To access the parameters passed to the, code will typically use the   table of that frame object. It's also possible to access the parameters passed to the template containing the  by using   and accessing that frame's.

Such a function can access the  object to get access to the parameters that the template was invoked with.

For detailed examples on passing information to your lua module

Loops and tables
Lua has several control structures .Control structures let your program make choices, or to run the same piece of code many times.

See control statement and loop and table practical examples for more elaborate use cases.

Lua libraries
Lua has a number of built-in libraries, such as the table library and the math library, and you can read about them at Standard Libraries. These supply variants of many of the standard features found in other popular programming languages like PHP and Python, such as regular expressions and string handling functions. Because Lua can access libraries written in C, custom extensions can be implemented.

See Lua standard libraries and Lua libraries tasks for more details.

MediaWiki libraries
All Scribunto libraries are located in the table.

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

mw.clearLogBuffer
Removes all data logged with.

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  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.

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

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

Returns the current frame object.

mw.getLogBuffer
Returns the data logged by, 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 on 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 #value, next, 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.

Global modules
Modules containing tables can also be retrieved from a global repository ( specifically dev.wikia.com). This uses a syntax such as:

The code above will load a table from a module stored in dev.wikia.com/wiki/Module:Convert/data (if it exists). Note: This is case sensitive.

mw.log
Passes the arguments to, 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 frame.args.name) 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 are 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, Fandom!". 

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

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

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

frame:preprocess
This can be represented as. It  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" — 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 wiki text string to pass to this method. It's faster and less prone to error if the arguments contain pipe characters or other wiki markups.

frame:getArgument
This is represented as ,.

It 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:preprocess( text ).

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

frame:argumentPairs
Same as.

Included for backwards compatibility.

frame:getTitle
Returns the title associated with the frame as a string.

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

Functions documented as  are available on the global   functions documented as   are methods of a language object.

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

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.

The methods below must all use the language object (e.g. lang).

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, honouring any special rules for the given language.

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

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

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

When the Ustring library is loaded, the  function is implemented as a call to

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

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.

With the second parameter, one can prevent the output from containing commas, as shown below:

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

The timestamp is the actual date. It accepts dates with either a backslash or dash e.g. "2015/10/20" or "2015-10-20".

The format string and supported values for  are identical to those for the  parser function from  ParserFunctions, as shown below:

Note that backslashes may need to be doubled in the Lua string where they wouldn't in wikitext:

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

This library allows one to do arithmetic in multiple supported languages (simultaneously), and is better than the  parser function:

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  to generate grammatically-correct text whether there is only 1 sock or 200 socks.

mw.language:convertGrammar
Note the different parameter order between the two aliases. convertGrammar 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  Magic words Localisation.

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

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: subject: Reference to the corresponding subject namespace's data.
 * 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.
 * aliases: List of aliases for the namespace.
 * 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 See mw.site.namespaces for details.

mw.site.sassParams
Table holding SASS utility parameters, including Theme Designer color variables.

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.
 * users: Number of users in the wiki.
 * activeUsers: Number of active users in the wiki.
 * admins: Number of users in group 'sysop' in the wiki.

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

If  is one of the above keys, just the corresponding value is returned instead.
 * all: Total pages, files, and subcategories.
 * subcats: Number of subcategories.
 * files: Number of files.
 * pages: Number of pages.

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 reversible, 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; "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:

The following properties are also available:
 * 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.

tostring will give the URI string.
 * 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

Methods of the URI object are:

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

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

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

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

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

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

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

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

mw.ustring.byteoffset
Returns 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 l 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 init offset is in characters rather than bytes.

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

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

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

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

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

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

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

If the Language library is also loaded, this will instead call  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 init offset is in characters rather than bytes.

mw.ustring.rep
Identical to.

mw.ustring.sub
Much like, 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:

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.
 * %a: represents all characters with General Category "Letter".
 * %c: represents all characters with General Category "Control".
 * %d: represents all characters with General Category "Decimal Number".
 * %l: represents all characters with General Category "Lowercase Letter".
 * %p: represents all characters with General Category "Punctuation".
 * %s: represents all characters with General Category "Separator", plus tab, linefeed, carriage return, vertical tab, and form feed.
 * %u: represents all characters with General Category "Uppercase Letter".
 * %w: represents all characters with General Category "Letter" or "Decimal Number".
 * %x: adds fullwidth character versions of the hex digits.

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  ; functions documented as   are methods of an mw.html object (see mw.html.create)

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.create

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 html:attr 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.

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

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

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

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

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

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

Examples, using the default values for the messages:

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


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

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

For example,  would return a table.

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

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

mw.text.tag
Generates an HTML-style tag for.

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

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

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

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

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

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

mw.text.unstrip
Replaces MediaWiki strip markers with the corresponding text. Note that the content of the strip marker does not necessarily correspond to the input, nor do they necessarily match the final page output.

Note that strip markers are typically used for a reason, and replacing them in Lua rather than allowing the parser to do so at the appropriate time may break things.

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

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

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

mw.title.new
Creates a new title object. The expensive function count will be incremented if the title object created is not for the current page and is not for a title that has already been loaded.


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

mw.title.makeTitle
Creates a title object with title  in namespace , optionally with the specified fragment and ,code>interwiki prefix. may be any key found in. If the resulting title is not valid, returns nil. This function is expensive under the same conditions as, and records a link just as does.

Note that  will create an object for the page Module:Foo, while   will create an object for the page Template:Module:Foo.

Note some of the properties below are methods and other are fields or variables in the title object, as shown in the example:

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

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

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

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

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

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

mw.message.newFallbackSequence
Wraps the value so that it will not be parsed as wikitext by msg:parse.

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

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

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

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

Returns the  object, to allow for call chaining.

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

Returns the  object, to allow for call chaining.

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

The default language is the one returned by.

Returns the  object, to allow for call chaining.

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

The default is true.

Returns the  object, to allow for call chaining.

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

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

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

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