Globals¶
Lua and Roblox global functions, from the Roblox creator-docs.
Luau globals¶
A list of functions and variables that are native to Luau.
Properties¶
_G¶
A table that is shared between all scripts of the same context level. Any
value written to _G from one script is visible to every other script at
that same context level, which makes it a simple way to share state
between scripts.
-- Script A (sets a value)
_G.mySharedValue = "hello from Script A"
Note that relying on `_G` for cross-script communication introduces
ordering dependencies and makes code harder to reason about. Prefer
`Class.ModuleScript` for shared state when possible.
_VERSION¶
A global variable that holds a string containing the current interpreter version.
A global variable (not a function) that holds a string containing the current interpreter version.
Functions¶
assert¶
Throws an error if the provided value resolves to false or nil.
Throws an error if the provided value is false or nil. If the
assertion passes, it returns all values passed to it.
collectgarbage¶
Performs the specified operation of the garbage collector. Note that
Roblox's Luau sandbox only allows the count option to be used (the total
memory in use by Luau, in kilobytes), as other options can interfere with
existing processes. Effectively, this makes Global.LuaGlobals.gcinfo() a
superior alternative that should be used instead.
error¶
Halts thread execution and throws an 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.
gcinfo¶
Returns the total memory heap size in kilobytes. The number reflects the current heap consumption from the operating system perspective, which fluctuates over time as garbage collector frees objects.
getfenv¶
Returns the current environment in use by the caller, as a dictionary.
- If provided with a function, the environment of the function will be returned.
- If provided with an integer,
Global.LuaGlobals.getfenv()will provide the environment of the function at the provided stack level: Level 1 is the function callingGlobal.LuaGlobals.getfenv(). Ifstackis0,Global.LuaGlobals.getfenv()returns the global environment of the current script. When usingGlobal.LuaGlobals.getfenv()to get the current environment of a script, it will return the same table every time within the specific thread.
WARNING: This function allows uncontrolled change of the global/function environment and disables script optimizations. Changes to the environment are not tracked by the script analysis tooling and may result in missing or incorrect warnings. As a replacement, consider using debug.info() instead.
Nova note: Legacy environment APIs exist but are sandbox-restricted.
getmetatable¶
Returns the metatable of the given value.
Returns the metatable of the given value 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.
t can be a value of any type, not only a table, and this function
doesn't error when t isn't a table. However, it doesn't always return
nil for non-table values. Strings and many Roblox types, such as
Instance, have locked metatables, so this function returns the
string "The metatable is locked" for them. To check whether a value uses
a specific metatable, compare the result directly, such as
getmetatable(value) == MyClass.
ipairs¶
Returns an iterator function and the table for use in a for loop.
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:
loadstring¶
Returns the provided code as a function that can be executed.
Loads Luau code from a string and returns it as a function.
Unlike standard Lua 5.1, Roblox's Luau cannot load the compiled bytecode
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
Global.LuaGlobals.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 Global.LuaGlobals.getfenv() and
Global.LuaGlobals.setfenv().
newproxy¶
Creates a blank userdata, with the option for it to have a metatable.
Creates a blank zero-size userdata with the option for it to have a
metatable. If addMetatable is true, an empty metatable is created and
assigned to the userdata; you can then retrieve it with
Global.LuaGlobals.getmetatable() and populate it with metamethods. If
addMetatable is false or omitted, the userdata has no metatable and
only serves as a unique identity token.
Unlike host-created userdata (Roblox instances), a newproxy-created
userdata always reports "userdata" from both Global.LuaGlobals.type()
and typeof(); setting a __type metamethod on it does not change the
typeof() result.
-- Create a proxy with a metatable to implement custom tostring
local proxy = newproxy(true)
local mt = getmetatable(proxy)
mt.__tostring = function()
return "MyProxy"
end
print(tostring(proxy)) --> MyProxy
print(type(proxy)) --> userdata
next¶
An iterator function for use in for loops.
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.
pairs¶
Returns an iterator function and the provided table for use in a for
loop.
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:
pcall¶
Runs the provided function and catches any error it throws, returning the function's success and its results.
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.
print¶
Prints all provided values to the output.
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.
rawequal¶
Returns whether v1 is equal to v2, bypassing their metamethods.
Checks whether v1 is equal to v2 without invoking the __eq
metamethod. The comparison uses primitive equality rules: values of
different types are never equal; nil equals only itself; numbers and
vectors are compared by value; booleans are compared by value; and all
reference types (tables, functions, threads, userdata) are compared by
identity (same object in memory).
This is useful when you need to compare two tables or userdata objects
that have an __eq metamethod and you want to test whether they are
literally the same object rather than semantically equal.
local a = setmetatable({}, {__eq = function() return true end})
local b = setmetatable({}, {__eq = function() return true end})
print(a == b) --> true (metamethod fires)
print(rawequal(a, b)) --> false (different objects)
print(rawequal(a, a)) --> true (same object)
rawget¶
Gets the real value of table[index], bypassing any metamethods.
Gets the real value of table[index] without invoking the __index
metamethod. The first argument must be a table; the second can be any
non-nil value. If the key does not exist in the table itself, rawget()
returns nil rather than walking up the metatable chain.
This is useful for inspecting a table's own stored fields when a metatable-based lookup chain would otherwise intercept the access.
local fallback = {x = 10}
local t = setmetatable({}, {__index = fallback})
print(t.x) --> 10 (found via __index)
print(rawget(t, "x")) --> nil (not in t itself)
t.y = 20
print(rawget(t, "y")) --> 20 (stored directly in t)
rawlen¶
Returns the length of the string or table, bypassing any metamethods.
Returns the length of a table or string without invoking the __len
metamethod. The argument must be a table or string; passing any other type
raises an argument error. For tables, the result is equivalent to what the
# operator would return before any metamethod fires; the length of the
array portion as determined by the boundary search. For strings, it
returns the byte count.
local t = setmetatable({1, 2, 3}, {__len = function() return 999 end})
print(#t) --> 999 (metamethod fires)
print(rawlen(t)) --> 3 (actual array length)
print(rawlen("hello")) --> 5
rawset¶
Sets the real value of table[index], bypassing any metamethods.
Sets table[index] to value without invoking the __newindex
metamethod. The first argument must be a table, the second is the key
(must not be nil), and the third is the value to assign. Returns the
table itself, which allows chained calls when building tables that have a
__newindex guard.
This is the complement of Global.LuaGlobals.rawget() for write
operations; use it when you need to bypass a proxy table's write
interception.
local log = {}
local proxy = setmetatable({}, {
__newindex = function(_, k, v)
table.insert(log, k)
rawset(proxy, k, v) -- actually store the value
end
})
rawset(proxy, "x", 42) -- bypasses __newindex; no log entry
proxy.y = 7 -- triggers __newindex; log entry created
print(proxy.x, proxy.y) --> 42 7
print(#log) --> 1 (only "y" was logged)
require¶
Returns the value that was returned by the given ModuleScript, running it if it has not been run yet.
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
Global.LuaGlobals.require(), mimicking the Unix-like semantics of Luau's
require() expression.
Specifically, require-by-string's resolution semantics are as follows:
- Paths with the
./prefix begin resolution atscript.Parent. - Paths with the
../prefix begin resolution atscript.Parent.Parent. - Paths with the
@self/prefix begin resolution atscript. - Paths with the
@game/prefix begin resolution atgame. - Each non-prefix component in a given path corresponds to a child
instance of the previous component. The exception to this is the
..component, which corresponds to the parent of the previous component. - If the desired ModuleScript is not present at the time that
Global.LuaGlobals.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.
To illustrate this, each pair of Global.LuaGlobals.require() expressions
in the example below contains two functionally equivalent calls. Redundant
parentheses have been added to clarify exactly how each path component
maps onto an instance.
Once the return object is created by an initial
Global.LuaGlobals.require() call of a ModuleScript, future
Global.LuaGlobals.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
Global.LuaGlobals.require() call will be supplied. This behavior allows
for the sharing of values across different scripts, as multiple
Global.LuaGlobals.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 Global.LuaGlobals.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 Global.LuaGlobals.require() function on the asset
ID of the ModuleScript, though only on the server.
select¶
Returns all arguments after the given index.
Returns all arguments after argument number index. If negative, it will
return from the end of the argument list.
If the index argument is set to "#", the number of arguments that were
passed after it is returned.
setfenv¶
Sets the given function's environment.
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.
If f is 0, then setfenv() changes the environment of the running
thread and returns no values.
WARNING: This function allows uncontrolled change of the global/function environment and disables script optimizations. Changes to the environment are not tracked by the script analysis tooling and may result in missing or incorrect warnings.
Nova note: Legacy environment APIs exist but are sandbox-restricted.
setmetatable¶
Sets the given table's metatable.
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.
tonumber¶
Returns the provided value converted to a number, or nil if impossible.
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.
tostring¶
Returns the provided value converted to a string, or nil if impossible.
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.
type¶
Returns the basic type of the provided object.
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", "userdata", and "buffer". The buffer and vector
primitives are additions from Luau, not from Lua.
unpack¶
Returns all elements from the given list as a tuple.
Returns the elements from the given list as separate return values,
equivalent to list[i], list[i+1], ..., list[j]. By default, i is 1
and j is the length of list (as defined by the # operator). If the
range is empty (i > j), no values are returned. An error is raised if
the requested range is too large to fit on the stack.
local t = {10, 20, 30, 40, 50}
print(unpack(t)) --> 10 20 30 40 50
print(unpack(t, 2, 4)) --> 20 30 40
-- Common pattern: forwarding a stored argument list
local args = {1, "hello", true}
someFunction(unpack(args))
xpcall¶
Similar to Global.LuaGlobals.pcall() except it uses a custom error
handler.
This function is similar to Global.LuaGlobals.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 Global.LuaGlobals.pcall(), the err function preserves the stack
trace of function f, which can be inspected using debug.info()
or debug.traceback().
Roblox globals¶
Built-in functions and constants unique to Roblox.
Properties¶
Enum¶
Contains all Enum objects.
A reference to the Enums data type, which stores all of the available enums that can be used on Roblox.
game¶
Refers to the DataModel singleton, the root instance of a place's hierarchy.
A reference to the DataModel, which is the root Instance of Roblox's parent/child hierarchy.
plugin¶
Refers to a Plugin singleton when the code is run in the context of a Studio plugin.
A reference to the Plugin object that represents the plugin being run from this Script. This reference exists only in the context where a script is executed as a plugin and is not passed to ModuleScripts within the plugin. To use this reference in a ModuleScript, you must explicitly pass it.
shared¶
A table shared between all code running at the same execution context level.
A table that is shared across all scripts that share the same execution
context level. This serves the exact same purpose as _G.
script¶
A reference to the LuaSourceContainer object (Script, LocalScript, or ModuleScript) that is executing this code.
A reference to the script object that is executing the code you are writing. It can be either a Script, a LocalScript, or a ModuleScript. This variable is not available when executing code from Roblox Studio's command bar.
workspace¶
A reference to the Workspace service, which contains all of the physical components of a place.
A reference to the Workspace service, which contains all of the physical components of a Roblox world.
Functions¶
delay¶
Schedules a function to be called on the next Heartbeat after the given duration (in seconds) has passed, with throttling.
Schedules a function to be executed after delayTime seconds have passed,
without yielding the current thread. This function allows multiple Luau
threads to be executed in parallel from the same stack. The delay will
have a minimum duration of 29 milliseconds, but this minimum may be higher
depending on the target framerate and various throttling conditions. If
the delayTime parameter is not specified, the minimum duration will be
used.
Nova note: Prefer task.delay in new code.
DebuggerManager¶
Refers to the legacy DebuggerManager class which acts as an interface
for the Luau debugger feature.
Returns the legacy DebuggerManager class which acts as an interface for
Roblox's Luau debugger feature.
This function is not recognized by Luau's analysis tool and will raise an undefined global warning.
elapsedTime¶
Returns the amount of time in seconds that the current instance of Roblox has been running for.
Returns how much time has elapsed since the current instance of Roblox was started. In Roblox Studio, this begins counting up from the moment Roblox Studio starts running, not just when opening a place.
PluginManager¶
Refers to the PluginManager, a deprecated singleton that was previously required to create plugins.
Returns the PluginManager which is a deprecated singleton that was previously required to create plugins. It still has some applicable uses, such as if you need to create a Plugin object from Studio's Command Bar.
printidentity¶
Prints "Current identity is X", where X corresponds to the current thread's security context level.
Prints Current identity is [ID] to the output, where [ID] corresponds to
the current thread's security context level.
settings¶
Returns the GlobalSettings object, which can be used to access the settings objects that are used in Roblox Studio's settings menu.
spawn¶
Calls a function immediately through the engine scheduler, with throttling.
Runs the specified callback function in a separate thread, without yielding the current thread.
The function will be executed the next time Roblox's Task Scheduler runs an update cycle. This delay will take at least 29 milliseconds but can arbitrarily take longer, depending on the target framerate and various throttling conditions.
The callback function is invoked with two arguments:
- The first being the amount of time which elapsed from when spawn was called to when the function was invoked.
- The second being equivalent to elapsedTime() or roughly how long the engine has been running.
Nova note: Prefer task.spawn in new code.
stats¶
Returns the Stats service.
Returns the Stats service. It is preferred that developers use ServiceProvider.GetService() to retrieve it instead.
tick¶
Returns the amount of time in seconds since the Unix epoch according to this device's time.
Returns how much time has elapsed, in seconds, since the Unix epoch, on the current local session's computer. The Unix epoch is represented by 00:00:00 on 1 January 1970.
tick() isn't officially deprecated, but has a variety of issues. It can
be off by up to one second and returns inconsistent results across time
zones and operating systems. Use os.time(),
os.clock(), or Global.RobloxGlobals.time() instead. Also
consider DateTime.UnixTimestamp and
DateTime.UnixTimestampMillis.
time¶
Returns the amount of time in seconds that has elapsed since the current game instance started running.
Returns the amount of time, in seconds, that has elapsed since the current
game instance started running. If the current game instance is not
running, this will be 0.
If Workspace.AuthorityMode is AuthorityMode.Server, this value is synchronized between client and server.
typeof¶
Returns the type of the given object as a string, also supporting Roblox-specific types (e.g. Vector3).
Returns the type of the object specified, as a string. This function is
more accurate than Luau's native type function, as it does not denote
Roblox-specific types as userdata.
UserSettings¶
Returns the UserSettings object, which is used to read information from the current user's game menu settings.
Returns the UserSettings object, which is used to read information from the current user's game menu settings.
version¶
Returns the current version of Roblox as a string, which includes the generation, version, patch and commit.
Returns the current version of Roblox as a string. The integers in the version string are separated by periods, and each integers represent the following, in order:
- Generation - The current generation of the application shell that is hosting the client.
- Version - The current release version of Roblox.
- Patch - The current patch number for this version of Roblox.
- Commit - The ID of the last internal commit that was accepted into this version of the client.
wait¶
Yields the current thread until the specified amount of time in seconds have elapsed, with throttling.
Yields the current thread until the specified amount of seconds have elapsed.
The delay will have a minimum duration of 29 milliseconds, but this
minimum may be higher depending on the target framerate and various
throttling conditions. If the seconds parameter is not specified, the
minimum duration will be used. This function returns:
- Actual time yielded (in seconds).
- Total time since the software was initialized (in seconds).
Nova note: Legacy 30 Hz wait is preserved; returns elapsed time.
warn¶
Behaves similarly to print, except with more distinct formatting (yellow); intended for messages which describe potential problems.
Behaves identically to Luau's print function, except the output is styled as a warning, with yellow text and a timestamp. This function accepts any number of arguments, and will attempt to convert them into strings which will then be joined together with spaces between them.
ypcall¶
Legacy function to work around an old task scheduling limitation of
Global.LuaGlobals.pcall(); should not be used for new work (use
Global.LuaGlobals.pcall() instead).