Lua reference manual/Standard libraries

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

_G


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

foo = 1 mw.log( foo ) -- logs "1" _G.foo = 2 mw.log( foo ) -- logs "2" _G = {}      -- _G no longer points to the global variable table _G.foo = 3 mw.log( foo ) -- still logs "2"

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

-- Call a function whose name is stored in a variable _G[var]

-- Log the names and stringified values of all global variables for k, v in pairs( _G ) do   mw.log( k, v ) end

-- Log the creation of new global variables setmetatable( _G, {    __newindex = function ( t, k, v )          mw.log( "Creation of new global variable '" .. k .. "'" )         rawset( t, k, v )     end } )

_VERSION


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

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

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

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

-- This doesn't check for errors local result1, result2, etc = func( ... ) -- This works the same, but does check for errors local result1, result2, etc = assert( func( ... ) )

error
Issues an error, with text.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

for k, v in pairs( t ) do    block end

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

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

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

In pseudocode,  might be defined something like this:

function pcall( f, ... ) try return true, f( ... ) catch ( message ) return false, message end end

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

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

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

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

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

function select( index, ... ) local t = { ... }    if index == '#' then return #t else return unpack( t, index ) end end

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

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

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

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

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

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

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

type
Returns the type of  as a string: "nil", "number", "string", "boolean", "table", or "function".

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

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

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

In pseudocode,  might be defined something like this:

function xpcall( f, errhandler ) try return true, f catch ( message ) message = errhandler( message ) return false, message end end

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

math.abs
Returns the absolute value of.

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

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

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

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

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

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

math.cosh
Returns the hyperbolic cosine of.

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

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

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

math.fmod
Returns the remainder of the division of  by   that rounds the quotient towards zero.

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

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

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

math.log
Returns the natural logarithm of.

math.log10
Returns the base-10 logarithm of.

math.max
Returns the maximum value among its arguments.

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

math.min
Returns the minimum value among its arguments.

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

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

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

math.pow
Equivalent to.

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

math.random
Returns a pseudo-random number.

The arguments  and   may be omitted, but if specified must be convertible to integers.
 * With no arguments, returns a real number in the range $$[0,1)$$
 * With one argument, returns an integer in the range $$[1,m]$$
 * With two arguments, returns an integer in the range $$[m,n]$$

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

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

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

math.sinh
Returns the hyperbolic sine of.

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

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

math.tanh
Returns the hyperbolic tangent of.

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

os.date

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

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

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

If  starts with '!', then the date is formatted in UTC rather than the server's local time. After this optional character, if format is the string "*t", then date returns a table with the following fields:
 * year (full)
 * month (1–12)
 * day (1–31)
 * hour (0–23)
 * min (0–59)
 * sec (0–60)
 * wday (weekday, Sunday is 1)
 * yday (day of the year)
 * isdst (daylight saving flag, a boolean; may be absent if the information is not available)

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

os.difftime
Returns the number of seconds from  to.

os.time
Returns a number representing the current time.

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

require
Loads the specified module.

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

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

See the documentation for  for information on the loaders available.

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.

For example, if you have a module "Module:Giving" containing the following: You can load this in another module with code such as this:

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

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

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

Note that the standard Lua loaders are not included.

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

package.seeall
Sets the __index metamethod for  to _G.

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

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 Scribunto Ustring library.

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

string.char
Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the byte value equal to its corresponding argument. See mw.ustring.char for a similar function that uses Unicode codepoints rather than byte values.

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

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

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

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

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

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

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

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

Identical to mw.ustring.format.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

string.sub
Returns the substring of  that starts at   and continues until  ;   and   can be negative. If  is nil or omitted, -1 is used.

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

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

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

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

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

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

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

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


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

Pattern items
A pattern item can be


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


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

Pattern
A pattern is a sequence of pattern items.

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

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

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

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

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

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

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

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

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

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

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

function table.maxn( table ) local maxn, k = 0, nil repeat k = next( table, k ) if type( k ) == 'number' and k > maxn then maxn = k        end until not k    return maxn end

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

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

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

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