Collapse Sidebar

Lua Globals

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.


Variant assert ( Variant value, string errorMessage = "assertion failed!" )

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 * 4
assert(product == 360, "Oh dear, multiplication is broken")
-- The line above does nothing, because 90 times 4 is 360
Variant collectgarbage ( string operation )

Performs an operation on the Lua garbage collector based on the specified option.

Roblox’s Lua sandbox only allows the “count” option to be used, so none of the other standard options are available.

The “count” option returns the total memory in use by Lua (in kilobytes).

void error ( string message, int level = 1 )

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

table getfenv ( Variant stack = 1 )

Returns the current environment in use by the caller.

  • If provided with a function, the environment of the function will be returned.
  • If provided with an integer, getfenv will provide the environment of the function at the provided stack level: Level 1 is the function calling getfenv. If stack is 0, getfenv returns the global environment of the current script. When using getfenv to get the current environment of a script, it will return the same table every time within the specific thread.


Getting the Current Environment
myVariable = "Hello, environments" -- Note: a global variable (non-local)
local env = getfenv()
print(env["myVariable"]) --> Hello, environments
Getting the Environment of a Function
function printMessage()
local env = getfenv(printMessage)
env.message = "Hello, function environments"
printMessage() --> Hello, function environments
Getting the Environment Based on Stack
function whatIsThePassword()
    local env = getfenv(1) -- Get the environment 1 level up, or whatever called this function
    print(env.password) -- Get the password from the environment one level up
    print(password) --> nil

function openSesame()
   local password = "secret" -- A variable local to openSesame
Variant getmetatable ( Variant t )

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
function , array , int ipairs ( array t )

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", "orangs", "kiwi"}
for index, fruit in ipairs(fruits) do
   print(index, fruit) --> 1 applies, 2 oranges, 3 kiwi, etc...
Variant loadstring ( string contents )

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.

userdata newproxy ( bool addMetatable = false )

Creates a blank userdata, with the option for it to have a metatable.

Variant , Variant next ( table t, Variant lastKey = nil )

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.

function , table pairs ( table t )

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) do
   print(name .. " has score: " .. score) -- "John has score: 5" etc
bool , Variant pcall ( function func, Tuple args )

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.

void print ( Tuple params )

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 will metatables for the the __tostring metamethod.

bool rawequal ( Variant v1, Variant v2 )

Checks whether v1 is equal to v2, without invoking any metamethod.

Variant rawget ( table t, Variant index )

Gets the real value of table[index], without invoking any metamethod.

table rawset ( table t, Variant index, Variant value )

Sets the real value of table[index] to a given value, without invoking any metamethod.

Tuple select ( int index, Tuple args )

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 C
print(select(-1, "A", "B", "C")) --> C
int select ( string cmd, Tuple args )

Returns the total number of arguments that were passed after the cmd argument, which must be "#" to use select in this fashion.

print(select("#", "A", "B", "C")) --> 3
Variant setfenv ( Variant f, table fenv )

Sets the environment to be used by the given function. f can be a function or a number that specifies the function at that stack level: Level 1 is the function calling setfenv. setfenv returns the given function.

As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values.

table setmetatable ( table t, Variant newMeta )

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
Variant tonumber ( Variant arg, int base = 10 )

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 error
print(assert(tonumber("roblox"))) --> Error: assertion failed
string tostring ( Variant e )

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
string type ( Variant v )

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”, “function”, “thread”, and “userdata”.

Variant unpack ( table list, int i = 1, int j = #list )

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.

bool , Variant xpcall ( function f, function err, tuple args )

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.


array _G

A table that is shared between all scripts of the same context level.

string _VERSION

A global variable (not a function) that holds a string containing the current interpreter version.