Lua globals
The following is a list of functions and variables that are native to Lua. These functions can be used in a standard installation of Lua 5.1.4, though there are some differences in how some of these work on Roblox.
Summary
Functions
Throws an error if the provided value resolves to false or nil.
Halts thread execution and throws an error.
Returns the total memory heap size in kilobytes.
Returns the metatable of the given table.
Returns an iterator function and the table for use in a for loop.
Returns the provided code as a function that can be executed.
Creates a blank userdata, with the option for it to have a metatable.
An iterator function for use in for loops.
Returns an iterator function and the provided table for use in a for loop.
Runs the provided function and catches any error it throws, returning the function's success and its results.
Prints all provided values to the output.
Returns whether v1 is equal to v2, bypassing their metamethods.
Gets the real value of table[index], bypassing any metamethods.
Returns the length of the string or table, bypassing any metamethods.
Sets the real value of table[index], bypassing any metamethods.
Returns the value that was returned by the given ModuleScript, running it if it has not been run yet.
Returns all arguments after the given index.
Sets the given table's metatable.
Returns the provided value converted to a number, or nil if impossible.
Returns the provided value converted to a string, or nil if impossible.
Returns the basic type of the provided object.
Returns all elements from the given list as a tuple.
Similar to pcall() except it uses a custom error handler.
Functions
assert
Throws an error if the provided value is false or nil. If the assertion passes, it returns all values passed to it.
local product = 90 * 4assert(product == 360, "Oh dear, multiplication is broken")-- The line above does nothing, because 90 times 4 is 360
Parameters
The value that will be asserted against.
The text that will be shown in the error if the assertion fails.
Returns
error
Terminates the last protected function called and outputs message as an error message. If the function containing the error is not called in a protected function such as pcall(), then the script which called the function will terminate. The error function itself never returns and acts like a script error.
The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.
Parameters
The error message to display.
The level of information that should be printed. Defaults to 1.
Returns
getmetatable
Returns the metatable of the given table t if it has one, otherwise returns nil. If t does have a metatable, and the __metatable metamethod is set, it returns that value instead.
-- Demonstrate getmetatable:local meta = {}local t = setmetatable({}, meta)print(getmetatable(t) == meta) --> true-- Make the original metatable unrecoverable by setting the __metatable metamethod:meta.__metatable = "protected"print(getmetatable(t)) --> protected
Parameters
The object to fetch the metatable of.
Returns
ipairs
Returns three values: an iterator function, the table t and the number 0. Each time the iterator function is called, it returns the next numerical index-value pair in the table. When used in a generic for-loop, the return values can be used to iterate over each numerical index in the table:
local fruits = {"apples", "oranges", "kiwi"}for index, fruit in ipairs(fruits) doprint(index, fruit) --> 1 apples, 2 oranges, 3 kiwi, etc...end
Parameters
A table whose elements are to be iterated over.
loadstring
Loads Lua code from a string and returns it as a function.
Unlike standard Lua 5.1, Roblox's Lua cannot load the binary version of Lua using loadstring().
loadstring() is disabled by default. For guidance around enabling it, see ServerScriptService.
WARNING: This method disables certain Luau optimizations on the returned function. Extreme caution should be taken when using loadstring(); if your intention is to allow users to run code in your experience, make sure to protect the returned function's environment by using getfenv() and setfenv().
Parameters
Returns
next
Returns the first key/value pair in the array. If a lastKey argument was specified then returns the next element in the array based on the key that provided. The order in which the indices are enumerated is not specified, even for numeric indices. To traverse a table in numeric order, use a numerical for loop or ipairs.
The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may, however, modify existing fields. In particular, you may clear existing fields.
Parameters
The array to be traversed.
The last key that was previously retrieved from a call to next.
Returns
pairs
Returns an iterator function, the passed table t, and nil, so that the construction will iterate over all key/value pairs of that table when used in a generic for loop:
local scores = {["John"] = 5,["Sally"] = 10}for name, score in pairs(scores) doprint(name .. " has score: " .. score)end
Parameters
An array or dictionary table to iterate over.
pcall
Calls the function func with the given arguments in protected mode. This means that any error inside func is not propagated; instead, pcall() catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall() also returns all results from the call, after this first result. In case of any error, pcall() returns false plus the error message.
Parameters
Returns
Receives any number of arguments, and prints their values to the output. print is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For a formatted output, use string.format(). On Roblox, print does not call tostring, but the __tostring metamethod still fires if the table has one.
Parameters
Any number of arguments to be outputted.
Returns
rawget
Gets the real value of table[index], without invoking any metamethods.
Parameters
The table to be referenced.
The index to get from t.
Returns
rawset
Sets the real value of table[index] to a given value, without invoking any metamethod.
Parameters
The table to be referenced.
The index to set in t to a specified value. Must be different from nil.
The value to be set to a specified index in table t.
Returns
require
Runs the supplied ModuleScript and returns what the ModuleScript returned (usually a table or a function). If the ModuleScript has not been run yet, it will be executed.
If a string path is provided instead, it is first resolved to a ModuleScript relative to the script that called require(), mimicking the Unix-like semantics of Luau's require() expression. For example, each pair of require() expressions in the example below contains two functionally equivalent calls.
-- "./" is equivalent to script.Parentrequire(script.Parent.ModuleScript)require("./ModuleScript")-- "../" is equivalent to script.Parent.Parentrequire(script.Parent.Parent.ModuleScript)require("../ModuleScript")
Specifically, require-by-string's resolution semantics are as follows:
- String paths must begin with either ./ or ../, where ./ is equivalent to script.Parent and ../ is equivalent to script.Parent.Parent.
- If the resolved path points to an Instance that is not a ModuleScript, require() will attempt to find a ModuleScript named Init or init parented to that Instance and use it instead, if it exists.
- If the desired ModuleScript is not present at the time that require() is called, the call will fail and throw an error. In other words, require-by-string is non-blocking: it does not implicitly wait for a ModuleScript to be created.
Once the return object is created by an initial require() call of a ModuleScript, future require() calls for the same ModuleScript (on the same side of the client-server boundary) will not run the code again. Instead, a reference to the same return object created by the initial require() call will be supplied. This behavior allows for the sharing of values across different scripts, as multiple require() calls from different scripts will reference the same returned object. If the returned object is a table, any values stored within the table are shared and accessible by any script requiring that ModuleScript.
As noted above, the "object sharing" behavior does not cross the client-server boundary. This means that if a ModuleScript is accessible to both the client and server (such as by being placed in ReplicatedStorage) and require() is called from both a LocalScript as well as a Script, the code in the ModuleScript will be run twice, and the LocalScript will receive a distinct return object from the one received by the Script.
Also note that if the ModuleScript the user wants to run has been uploaded to Roblox (with the instance's name being MainModule), it can be loaded by using the require() function on the asset ID of the ModuleScript, though only on the server.
Parameters
The ModuleScript that will be executed to retrieve the return value it provides, or a reference to one (a string path or asset ID).
Returns
What the ModuleScript returned (usually a table or a function).
select
Returns all arguments after argument number index. If negative, it will return from the end of the argument list.
print(select(2, "A", "B", "C")) --> B Cprint(select(-1, "A", "B", "C")) --> C
If the index argument is set to "#", the number of arguments that were passed after it is returned.
print(select("#", "A", "B", "C")) --> 3
Parameters
The index of the argument to return all arguments after in args. If it's set to "#", the number of arguments that were passed after it is returned.
A tuple of arguments.
Returns
setmetatable
Sets the metatable for the given table t to newMeta. If newMeta is nil, the metatable of t is removed. Finally, this function returns the table t which was passed to it. If t already has a metatable whose __metatable metamethod is set, calling this on t raises an error.
local meta = {__metatable = "protected"}local t = {}setmetatable(t, meta) -- This sets the metatable of t-- We now have a table, t, with a metatable. If we try to change it...setmetatable(t, {}) --> Error: cannot change a protected metatable
Parameters
The table to set the metatable of.
If nil, the metatable of the given table t is removed. Otherwise, the metatable to set for the given table t.
Returns
tonumber
Attempts to convert the arg into a number with a specified base to interpret the value in. If it cannot be converted, this function returns nil.
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 default), the number may have a decimal part, as well as an optional exponent part. In other bases, only unsigned integers are accepted.
If a string begins with 0x and a base is not provided, the 0x is trimmed and the base is assumed to be 16, or hexadecimal.
print(tonumber("1337")) --> 1337 (assumes base 10, decimal)print(tonumber("1.25")) --> 1.25 (base 10 may have decimal portions)print(tonumber("3e2")) --> 300 (base 10 may have exponent portion, 3 × 10 ^ 2)print(tonumber("25", 8)) --> 21 (base 8, octal)print(tonumber("0x100")) --> 256 (assumes base 16, hexadecimal)print(tonumber("roblox")) --> nil (does not raise an error)-- Tip: use with assert if you would like unconvertable numbers to raise an errorprint(assert(tonumber("roblox"))) --> Error: assertion failed
Parameters
The object to be converted into a number.
The numerical base to convert arg into.
Returns
tostring
Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use string.format. If the metatable of e has a __tostring metamethod, then it will be called with e as the only argument and will return the result.
local isRobloxCool = true-- Convert the boolean to a string then concatenate:print("Roblox is cool: " .. tostring(isRobloxCool)) --> Roblox is cool: true
Parameters
The object to be converted into a string.
Returns
type
Returns the type of its only argument, coded as a string. The possible results of this function are "nil" (a string, not the value nil), "number", "string", "boolean", "table", "vector", "function", "thread", and "userdata".
Parameters
The object to return the type of.
Returns
unpack
Returns the elements from the given table. By default, i is 1 and j is the length of list, as defined by the length operator.
Parameters
Returns
xpcall
This function is similar to pcall(), except that you can set a new error handler.
xpcall() calls function f in protected mode, using err as the error handler, and passes a list of arguments. Any error inside f is not propagated; instead, xpcall() catches the error, calls the err function with the original error object, and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In this case, xpcall() also returns all results from the call, after this first result. In case of any error, xpcall() returns false plus the result from err.
Unlike pcall(), the err function preserves the stack trace of function f, which can be inspected using debug.info() or debug.traceback().
Parameters
Returns
Properties
_G
A table that is shared between all scripts of the same context level.
_VERSION
A global variable (not a function) that holds a string containing the current interpreter version.