Fandom Developers Wiki
Advertisement

Reason: Not fully updated to Fandom's new Scribunto version (possibly from MediaWiki 1.33.3)..
Please replace any old information with up-to-date information (this may include rewriting code for compatibility changes).

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[]

_G[]

This variable holds a reference to the current global variable table; the global variable foo may also be accessed as _G.foo. 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[]

assert( v, message, ... )

If v is nil or false, issues an error. In this case, message 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 v is any other value, assert returns all arguments including v and message.

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 assert:

-- 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[]

error( message, level )

Issues an error, with text message.

error normally adds some information about the location of the error. If level is 1 or omitted, that information is the location of the call to error 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[]

getfenv( f )

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

Returns an environment (global variable table), as specified by f:

  • If 1, nil, or omitted, returns the environment of the function calling getfenv. 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 getfenv will return nil instead.

getmetatable[]

getmetatable( table )

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[]

ipairs( t )

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

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 __ipairs( t ) instead.

next[]

next( table, key )

This allows for iterating over the keys in a table. If key 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 next( t ) == nil.

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[]

pairs( t )

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

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

This will iterate over the key-value pairs in t 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 __pairs( t ) instead.

pcall[]

pcall( f, ... )

Calls the function f with the given arguments in protected mode. This means that if an error is raised during the call to f, 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, pcall might be defined something like this:

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

rawequal[]

rawequal( a, b )

This is equivalent to a == b except that it ignores any __eq metamethod.

rawget[]

rawget( table, k )

This is equivalent to table[k] except that it ignores any __index metamethod.

rawset[]

rawset( table, k, v )

This is equivalent to table[k] = v except that it ignores any __newindex metamethod.

select[]

select( index, ... )

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

In other words, select 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

Negative numbers count from the end of the table, e.g.:

local secondToLast, last = select(2, "one", "two", "three", "four")

mw.log(secondToLast) --> "two"
mw.log(last)         --> "three"

local secondToLast, last = select(-2, "one", "two", "three", "four")

mw.log(secondToLast) --> "three"
mw.log(last)         --> "four"

setmetatable[]

setmetatable( table, metatable )

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

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

tonumber[]

tonumber( value, base )

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

The optional base (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[]

tostring( value )

Converts value 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 __tostring( value ) instead.

type[]

type( value )

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

unpack[]

unpack( table, i, j )

Returns values from the given table, something like table[i], table[i+1], ···, table[j] would do if written out manually. If nil or not given, i defaults to 1 and j defaults to #table.

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

xpcall[]

xpcall( f, errhandler )

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

In pseudocode, xpcall 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 library[]

debug.traceback[]

debug.traceback( message, level )

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[]

math.abs[]

math.abs( x )

Returns the absolute value of x.

math.acos[]

math.acos( x )

Returns the arc cosine of x (given in radians).

math.asin[]

math.asin( x )

Returns the arc sine of x (given in radians).

math.atan[]

math.atan( x )

Returns the arc tangent of x (given in radians).

math.atan2[]

math.atan2( y, x )

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

math.ceil[]

math.ceil( x )

Returns the smallest integer larger than or equal to x.

math.cos[]

math.cos( x )

Returns the cosine of x (given in radians).

math.cosh[]

math.cosh( x )

Returns the hyperbolic cosine of x.

math.deg[]

math.deg( x )

Returns the angle x (given in radians) in degrees.

math.exp[]

math.exp( x )

Returns the value .

math.floor[]

math.floor( x )

Returns the largest integer smaller than or equal to x.

math.fmod[]

math.fmod( x, y )

Returns the remainder of the division of x by y that rounds the quotient towards zero.

math.frexp[]

math.frexp( x )

Returns two values m and e such that:

  • If x is finite and non-zero: , e is an integer, and the absolute value of m is in the range
  • If x is zero: m and e are 0
  • If x is NaN or infinite: m is x and e is not specified

math.huge[]

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

math.ldexp[]

math.ldexp( m, e )

Returns (e should be an integer).

math.log[]

math.log( x )

Returns the natural logarithm of x.

math.log10[]

math.log10( x )

Returns the base-10 logarithm of x.

math.max[]

math.max( x, ... )

Returns the maximum value among its arguments.

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

math.min[]

math.min( x, ... )

Returns the minimum value among its arguments.

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

math.modf[]

math.modf( x )

Returns two numbers, the integral part of x and the fractional part of x.

math.pi[]

The value of .

math.pow[]

math.pow( x, y )

Equivalent to x^y.

math.rad[]

math.rad( x )

Returns the angle x (given in degrees) in radians.

math.random[]

math.random( m, n )

Returns a pseudo-random number.

The arguments m and n may be omitted, but if specified must be convertible to integers.

  • With no arguments, returns a real number in the range
  • With one argument, returns an integer in the range
  • With two arguments, returns an integer in the range

math.randomseed[]

math.randomseed( x )

Sets x as the seed for the pseudo-random generator.

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

math.sin[]

math.sin( x )

Returns the sine of x (given in radians).

math.sinh[]

math.sinh( x )

Returns the hyperbolic sine of x.

math.sqrt[]

math.sqrt( x )

Returns the square root of x. Equivalent to x^0.5.

math.tan[]

math.tan( x )

Returns the tangent of x (given in radians).

math.tanh[]

math.tanh( x )

Returns the hyperbolic tangent of x.

Operating system library[]

os.clock[]

os.clock()

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

os.date[]

os.date( format, time )

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 format. If the format is omitted or nil, "%c" is used.

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

If format 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[]

os.difftime( t2, t1 )

Returns the number of seconds from t1 to t2.

os.time[]

os.time( table )

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

Package library[]

require[]

require( modulename )

Loads the specified module.

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

Otherwise, it calls each loader in the package.loaders 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 package.loaded[modulename] and is returned.

See the documentation for package.loaders 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:

local p = {}

p.someDataValue = 'Hello!'

return p

You can load this in another module with code such as this:

local giving = require( "Module:Giving" )

local value = giving.someDataValue -- value is now 'Hello!'

Global modules[]

Modules hosted in dev.wikia.com are called global modules because they can be loaded by other modules using a similar syntax to loading local modules.[1] The correct syntax to use is require("Dev:ModuleName") . This is case sensitive. It should also be added to all modules hosted on dev.wikia or else it'll attempt to use a module in a local wiki (e.g. crocodile.wikia.com).

You can load this in another module from another wiki with code such as this:

local giving = require( "Dev:Giving" )

local value = giving.someDataValue -- value is now 'Hello!'

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 package.preload[modulename] 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[]

package.seeall( table )

Sets the __index metamethod for table 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[]

string.byte( s, i, j )

If the string is considered as an array of bytes, returns the byte values for s[i], s[i+1], ···, s[j]. The default value for i is 1; the default value for j is i. Identical to mw.ustring.byte().

string.char[]

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[]

string.find( s, pattern, init, plain )

Looks for the first match of pattern in the string s. If it finds a match, then find returns the offsets in s 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 init specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument plain turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in pattern being considered "magic".

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

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

string.format[]

string.format( formatstring, ... )

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 printf 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[]

string.gmatch( s, pattern )

Returns an iterator function that, each time it is called, returns the next captures from pattern over string s. If pattern 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[]

string.gsub( s, pattern, repl, n )

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

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

If repl 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 repl 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[]

string.len( s )

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

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

string.lower[]

string.lower( s )

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[]

string.match( s, pattern, init )

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

A third, optional numerical argument init 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 init offset is in characters rather than bytes.

string.rep[]

string.rep( s, n )

Returns a string that is the concatenation of n copies of the string s. Identical to mw.ustring.rep().

string.reverse[]

string.reverse( s )

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

string.sub[]

string.sub( s, i, j )

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

In particular, the call string.sub(s,1,j) returns a prefix of s with length j, and string.sub(s, -i) returns a suffix of s with length i.

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

string.upper[]

string.upper( s )

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 {n,m} quantifier in PCRE).
  • The only zero-width assertions are ^, $, and the %f[set] "frontier" pattern; assertions such as PCRE's \b 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, "\0"). Use %z 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.
  • %a: represents all ASCII letters.
  • %c: represents all ASCII control characters.
  • %d: represents all digits.
  • %l: represents all ASCII lowercase letters.
  • %p: represents all punctuation characters.
  • %s: represents all ASCII space characters.
  • %u: represents all ASCII uppercase letters.
  • %w: represents all ASCII alphanumeric characters.
  • %x: represents all hexadecimal digits.
  • %z: represents ASCII NUL, the zero byte.
  • %A: All characters not in %a.
  • %C: All characters not in %c.
  • %D: All characters not in %d.
  • %L: All characters not in %l.
  • %P: All characters not in %p.
  • %S: All characters not in %s.
  • %U: All characters not in %u.
  • %W: All characters not in %w.
  • %X: All characters not in %x.
  • %Z: All characters not in %z.
  • %x: (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.
  • [set]: 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 %x described above can also be used as components in set. All other characters in set represent themselves. For example, [%w_] (or [_%w]) represents all alphanumeric characters plus the underscore, [0-7] represents the octal digits, and [0-7%l%-] represents the octal digits plus the lowercase letters plus the '-' character.

    The interaction between ranges and classes is not defined. Therefore, patterns like [%a-z] or [a-%%] have no meaning.

  • [^set]: 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;
  • %n, for n between 1 and 9; such item matches a substring equal to the n-th captured string (see below);
  • %bxy, 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 %b() matches expressions with balanced parentheses.
  • %f[set], 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 (a*(.)%w(%s*)), the part of the string matching a*(.)%w(%s*) is stored as the first capture (and therefore has number 1); the character matching . is captured with number 2, and the part matching %s* has number 3.

As a special case, the empty capture () captures the current string position (a number). For instance, if we apply the pattern "()aa()" on the string "flaaap", 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 table.foreach(), table.foreachi(), and table.getn() may be available but are deprecated. Use a for loop with pairs(), a for loop with ipairs(), and the length operator instead.

table.concat[]

table.concat( table, sep, i, j )

Given an array where all elements are strings or numbers, returns table[i] .. sep .. table[i+1] ··· sep .. table[j].

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

table.insert[]

table.insert( table, value )
table.insert( table, pos, value )

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

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

table.maxn[]

table.maxn( table )

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[]

table.remove( table, pos )

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

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

table.sort[]

table.sort( table, comp )

Sorts table elements in a given order, in-place, from table[1] to table[#table]. If comp 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 not comp(a[i+1],a[i]) will be true after the sort). If comp 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.

Optimization (Garbage Collector)[]

Methods for collecting and flushing garbage[2] are unavailable in Scribunto[3].

References[]

Advertisement