environment Docs /
Globals
Globals
globals
Global functions and values of the dreamwork environment.
Constants Name Type Description _Gshared _GThe global environment of Lua. _Rtable The registry of Lua. LUA_VERSIONinteger The version of the Lua interpreter. GAME_VERSIONinteger Contains the version number of the Garrys Mod. For example: 201211 = 01.01.2012 GAME_BRANCH"x86-64" | "dev" | "prerelease" | "unknown" | string The branch the Garry's Mod is running on. This will be unknown on main branch. LUA_REALM"server" | "client" | "menu" | "unknown" The realm the code is running on. LUA_CLIENTboolean true if code is running on the client, false otherwise.LUA_CLIENT_SERVERboolean true if code is running on the client or server, false otherwise.LUA_SERVERboolean true if code is running on the server, false otherwise.DEVELOPERinteger A cached value of developer console variable. FRAME_TIMEnumber The time it takes to run one frame in seconds. Client-only FPSnumber The number of frames per second. Client-only TICK_TIMEnumber The measured time between ticks in seconds, averaged over half a second, the menu imitates a tick every frame. TPSnumber The measured number of ticks per second, averaged over half a second, the menu imitates a tick every frame. nullnull A sentinel symbol that represents an explicit "no value", compare it by identity. SYSTEM_OSXboolean true if the game is running on OSX.SYSTEM_LINUXboolean true if the game is running on Linux.SYSTEM_WINDOWSboolean true if the game is running on Windows.SYSTEM_X64boolean true if the game is running on 64-bit architecture.SYSTEM_X32boolean true if the game is running on 32-bit architecture.SYSTEM_NAME"osx64" | "osx" | "linux64" | "linux" | "win64" | "win32" The short name of the currently running system with architecture. SYSTEM_COUNTRYstring The country code of the operating system. (ISO 3166-1 alpha-2) SYSTEM_HAS_BATTERYboolean true if the operating system has a battery, false if not.SYSTEM_BATTERY_LEVELgarrysmod.system.BatteryPowerThe battery level, from 0 to 100. ffiffilib | nil WASMErrorWASMErrorClass
Functions apairsIterates over async iterator, calling it with given arguments. assertThrows an error if the value is false or nil, otherwise returns all its arguments, like assert. checktypeChecks that the local variable at the given stack index (in the calling function) matches one of the expected types/cla… checkvalueValidates a local variable of the calling function (typically one of its parameters) against one or more validator func… clearIntervalCancels an interval created by setInterval, so its callback will not be called anymore. clearTimeoutCancels a timeout created by setTimeout, so its callback will not be called. copyReturns the copy of the value. dispatchBuilds a function that dispatches each call to one of several implementations, chosen by the Lua types of the call's ar… dofileOpens the named file and executes its content as a Lua chunk. equalCompares two values for equality. errorThrows an error with the specified message and level. errorfThrows an error with a formatted message, blamed on the caller of the function that calls errorf. getfenvReturns the current environment in use by the function. getmetatableIf object does not have a metatable, returns nil. hashReturns the hash of the given value. importinextReturns the next value in the table t, with the given index. ipairsReturns three values (an iterator function, the table t, and 0) so that the construction for i,v in ipairs(t) do body e… isAngle3isBigFixedChecks whether the value is a BigFixed. isBigIntegerChecks whether the value is a BigInteger. isBooleanChecks whether the value type is boolean. isCallableChecks if the value is callable, basically it's a function or a table with a callable call metamethod. isClassChecks if the value is a class. isErrorReturns whether the given value is an error. isFunctionChecks whether the value type is a function. isHTMLNodeChecks whether the value type is a HTMLNode. isInstanceChecks if the value is an instance of the given parent. isIntegerChecks whether the value type is a integer. isNilChecks whether the value type is nil. isNumberChecks whether the value type is a number. isObjectChecks if the value is an object created by a class. isQuaternionisStringChecks whether the value type is a string. isSymbolChecks if a value is a symbol. isTableChecks whether the value is a table. isThreadChecks whether the value type is a thread. isTypeChecks if the value is an instance of the given parent. isURLChecks if the given value is a URL. isURLSearchParamsChecks if the given value is a URL.SearchParams. isValidChecks if the value is valid. isVector2isVector3isVMatrixisXMLNodeChecks whether the value type is a XMLNode. junctionCreates a function that accepts a variable number of arguments and returns them in the order of the specified indices. knextReturns the next non-integer key–value pair in the table tbl. kpairsReturns two values (an iterator function and the table tbl) so that the construction local t = { "a", "b", foo = 1, bar… lenReturns the length of the given value. lessEqualCompares two values, returning whether the first is less than or equal to the second. lessThanCompares two values, returning whether the first is less than the second. loadbinaryLoads a binary module if available. loadbytecodeLoads a string as a bytecode chunk in the specified environment and returns function as a compile result. loadfileLoads a file as a lua code chunk in the specified environment and returns function as a compile result. loadstringLoads a string as a lua code chunk in the specified environment and returns new function as a compile result. lookupbinaryChecks if a binary module is available and can be loaded. nextIf t has a metamethod pairs, calls it with t as argument and returns the first three results from the call. overloadWraps main_fn so that calls whose arguments match a specific type signature are routed to overload_fn instead, while ev… pairsIf t has a metamethod pairs, calls it with t as argument and returns the first three results from the call. printPrints the given arguments to the console. printDiffPrints the difference between two strings to the console. printfPrints a formatted string to the console. printTablePrints the contents of a table to the engine console as a colorized, indented, pseudo-Lua literal, recursing into any n… rangeCreates a stateless numeric for-loop iterator that steps from from to to (inclusive), incrementing (or decrementing) by… representReturns a string representation of the given value. requireLoads the given module, returns any value returned by the searcher(true when nil). setfenvSets the environment of the specified function. setIntervalCalls the fn function every delay seconds, until the interval is cancelled with clearInterval. setTimeoutCalls the fn function after delay seconds. sizeofReturns binary size of the value as integer of bit/bytes. sleepPuts current thread to sleep for given amount of seconds. SymbolGets or creates the symbol with the given name. toBigFixedCreates a BigFixed object from the given value. toBigIntCreates a BigInteger object from the given value. toBigIntegerCreates a BigInteger object from the given value. toboolIf e has a metamethod toboolean, calls it with e as argument and returns its result. tobooleanIf e has a metamethod toboolean, calls it with e as argument and returns its result. tocolorIf value has a metamethod tocolor, calls it with value as argument and returns its result. toErrorConverts any error value into an Error and captures its call stack if it has none yet. tohexReturns a hexadecimal string identifying the given value. tonumberIf e has a metamethod tonumber, calls it with e and base as arguments and returns its result. tostringReceives a value of any type and converts it to a string in a human-readable format. tryCalls the function in protected mode, converting a raised error into an Error. typeReturns a string representing the name of the type of the passed object. warnDisplays the error with its call stack without throwing it, the current code keeps running. yieldYields given arguments to the apairs listener.
async function apairs (iterator : async, ... : any ): async, thread
Iterates over async iterator, calling it with given arguments.
Example lua Copy
---@async
---@return AsyncIterator<number>
local function count ( from, to )
for i = from, to do
futures.yield ( i )
end
end
local function main ()
for i in futures.apairs ( count, 1 , 5 ) do
print ( i ) -- 1, 2, 3, 4, 5
end
end
futures.run ( main )
Parameters
Name Type Description iteratorasyncfun(...): futures.AsyncIterator<K, V> The async iterator function to drive. ...any Arguments to pass to iterator.
Returns
Type Name Description asyncfun(...): K, V thread
See also
function assert (value : T, message? : ( string | Error | ErrorClass )?, ... : any ): T, any
Throws an error if the value is false or nil, otherwise returns all its arguments, like assert.
The message can be:
nil, which throws "assertion failed!";a string, formatted with the remaining arguments when there are any; an Error , which is thrown as is; an error class, created with the string formatted from the remaining arguments. lua Copy
local file = assert ( open ( path ), "cannot open '%s'" , path )
assert ( size >= 0 , ValueError, "size must be positive, got %d" , size )
Parameters
Name Type Description valueTThe value to check. messageoptional ( string | Error | ErrorClass )?The error message, error object or error class. ...any The message format arguments.
Returns
Type Name Description Tvalueany ...
function checktype (index : integer , ... : any )
Checks that the local variable at the given stack index (in the calling function) matches one of the expected types/classes given in .... If the value's type/instance does not match any of the expected types, a TypeError is raised, otherwise the function returns without doing anything.
Parameters
Name Type Description indexinteger The stack index of the local variable to check (as used by debug.getlocal). ...any The expected type names (strings) or class/type tables (with an optional __type field) to check the value against.
function checkvalue (index : integer , ... : ( fun ( value: any ): true, nil ) | ( fun ( value: any ): false, string ))
Validates a local variable of the calling function (typically one of its parameters) against one or more validator functions, raising a ValueError on the first failure.
index is the index of the local variable in the function that called checkvalue, as in debug.getlocal. Parameters come first, so 1 is the first parameter, 2 the second, and so on. The variable's current value is read at call time, so reassigning a parameter before the check changes what gets validated.
Each validator receives the value and must return true if it is valid, or false plus an error message if it isn't. Validators run in the order given and checking stops at the first failure. Only a strict false counts as a failure, so a validator that returns nil (or nothing) is treated as passing.
On failure, the error is raised with level 2, so it points at the function that called checkvalue rather than at checkvalue itself.
lua Copy
local function is_positive ( value )
if value > 0 then
return true
end
return false , "must be positive"
end
local function set_speed ( speed )
checkvalue ( 1 , is_positive )
-- ...
end
Parameters
Name Type Description indexinteger The index of the calling function's local variable to validate (1 = its first parameter/argument). ...( fun ( value: any ): true, nil ) | ( fun ( value: any ): false, string )The validators to run, in order. Each returns true, or false and an error message.
function clearInterval (interval_id : integer ): boolean
Cancels an interval created by setInterval, so its callback will not be called anymore.
Usage example:
lua Copy
local interval_id = setInterval ( function ()
print ( "Hello, world!" )
end , 1 )
clearInterval ( interval_id )
Parameters
Name Type Description interval_idinteger The identifier of the interval returned by setInterval.
Returns
Type Name Description boolean is_clearedReturns true if the interval was found and cancelled, otherwise false.
function clearTimeout (timeout_id : integer ): boolean
Cancels a timeout created by setTimeout, so its callback will not be called.
Usage example:
lua Copy
local timeout_id = setTimeout ( function ()
print ( "This will never be printed." )
end , 5 )
clearTimeout ( timeout_id )
Parameters
Name Type Description timeout_idinteger The identifier of the timeout returned by setTimeout.
Returns
Type Name Description boolean is_clearedReturns true if the timeout was found and cancelled, otherwise false.
function copy (value : T): T
Returns the copy of the value.
Parameters
Name Type Description valueTThe value to copy.
Returns
Type Name Description TcopyThe copy of the value.
function dispatch (inputs : OverloadInput <F>[], fallback_fn? : F): F
Builds a function that dispatches each call to one of several implementations, chosen by the Lua types of the call's arguments. The multi-signature counterpart to overload, which only supports a single alternative signature.
Each entry in inputs pairs a match signature (a type name, or an ordered list of type names) with a fn. On every call, the entries are checked in order, and the first one whose signature matches exactly (same argument count, same types in the same order) has its fn called with the arguments. If nothing matches, fallback_fn is called instead; if there is no fallback_fn, an error is raised at call time.
inputs is validated up front: every fn must be a function and every match must be a string or a table, otherwise a TypeError is raised at definition time (level 2, pointing at the caller of dispatch). A bare string match is shorthand for a single-type list.
NOTE : inputs is modified in place. The entry count is cached in inputs[0], each match list gets its own count in match[0], and string match values are replaced with table equivalents. Don't reuse or edit the table after passing it in.
NOTE : a signature with no types can never match. Zero-argument calls always fall through to fallback_fn.
lua Copy
local describe = dispatch ( {
{ match = "string" , fn = function ( str ) return "a string" end },
{ match = { "number" , "number" }, fn = function ( a, b ) return "two numbers" end },
}, function ( ... ) return "something else" end )
describe ( "hi" ) --> "a string"
describe ( 1 , 2 ) --> "two numbers"
describe ( 1 ) --> "something else" (no signature matches: fallback_fn)
Parameters
Name Type Description inputsOverloadInput <F>[]The signatures to dispatch between, checked in order (first match wins). fallback_fnoptional FThe function called when no input matches. If omitted, a non-matching call raises an error.
Returns
Type Name Description Ffn_overA function that dispatches to the matching input's fn, or to fallback_fn.
function dofile (file_path : string , ... : any ): any
Opens the named file and executes its content as a Lua chunk.
When called without arguments, dofile executes the content of the standard input (stdin).
Returns all values returned by the chunk. In case of errors, dofile propagates the error to its caller. (That is, dofile does not run in protected mode.)
View documents
Parameters
Name Type Description file_pathstring ...any
Returns
Type Name Description any ...
function equal (a : any , b : any ): boolean
Compares two values for equality.
Unlike Lua's == operator, this function invokes the __eq metamethod from either operand if one is available. If neither operand defines __eq, it falls back to the built-in equality operator.
Parameters
Name Type Description aany The first value to compare. bany The second value to compare.
Returns
Type Name Description boolean is_equaltrue if the values are considered equal; otherwise false.
function error (value? : any , stack_level? : integer )
Throws an error with the specified message and level.
Parameters
Name Type Description valueoptional any The error value to throw. stack_leveloptional integer The stack level to throw the error.
function errorf (fmt : string , ... : any )
Throws an error with a formatted message, blamed on the caller of the function that calls errorf.
Use error( string.format( fmt, ... ), stack_level ) to pick another level.
Parameters
Name Type Description fmtstring The error message format. ...any The error message arguments to format/interpolate.
function getfenv (location : integer | function ): table
Returns the current environment in use by the function.
Parameters
Name Type Description locationinteger | function Can be a Lua function or a number that specifies the function at that stack level.
Returns
Type Name Description table fenvSpecified function environment.
function hash (value : any ): integer
Returns the hash of the given value.
Parameters
Name Type Description valueany The value to get the hash of.
Returns
Type Name Description integer hashThe hash of the given value.
function import (package_name : string , package_version : string ): any
Parameters
Name Type Description package_namestring package_versionstring
Returns
function inext (tbl : table , index : integer ): integer | nil , any
Returns the next value in the table t, with the given index.
Parameters
Name Type Description tbltable indexinteger
Returns
Type Name Description integer | nil any
function ipairs (t : V[]): (fun ( table : V[], i: ( integer | nil ) ): integer ), V, V[], integer
Returns three values (an iterator function, the table t, and 0) so that the construction
lua Copy
for i,v in ipairs (t) do body end will iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first absent index.
View documents
Parameters
Returns
Type Name Description fun ( table : V[], i: ( integer | nil ) ): integer VV[]integer i
function isAngle3 (value : any ): boolean
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_angle3
function isBigFixed (value : any ): boolean
Parameters
Name Type Description valueany The value to check.
Returns
Type Name Description boolean is_bigfixedtrue if the value is a BigFixed , false otherwise.
function isBigInteger (value : any ): boolean
Parameters
Name Type Description valueany The value to check.
Returns
Type Name Description boolean is_biginttrue if the value is a BigInteger , false otherwise.
function isBoolean (value : any ): boolean
Checks whether the value type is boolean.
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_bool
function isCallable (value : any ): boolean
Checks if the value is callable, basically it's a function or a table with a callable __call metamethod.
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_callable
function isClass (value : any ): boolean
Checks if the value is a class.
Parameters
Name Type Description valueany The value to check for being a class.
Returns
Type Name Description boolean is_classtrue if value is a class, false otherwise.
function isError (value : any ): boolean
Returns whether the given value is an error.
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_error
function isFunction (value : any ): boolean
Checks whether the value type is a function.
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_function
function isHTMLNode (value : any ): boolean
Checks whether the value type is a HTMLNode .
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_html_node
function isInstance (object : any , ... : any ): boolean
Checks if the value is an instance of the given parent.
Parameters
Name Type Description objectany The object to check for being an instance of the given parent. ...any The parent classes/metatables to check against.
Returns
Type Name Description boolean is_instancetrue if object is an instance of any of the given parent classes/metatables, false otherwise.
function isInteger (value : any ): boolean
Checks whether the value type is a integer.
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_integer
function isNil (value : any ): boolean
Checks whether the value type is nil.
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_nil
function isNumber (value : any ): boolean
Checks whether the value type is a number.
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_number
function isObject (value : any ): boolean
Checks if the value is an object created by a class.
Objects of a base that was never passed to class.create are not considered objects.
Parameters
Name Type Description valueany The value to check for being an object.
Returns
Type Name Description boolean is_objecttrue if value is an object created by a class, false otherwise.
function isQuaternion (value : any ): boolean
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_quaternion
function isString (value : any ): boolean
Checks whether the value type is a string.
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_string
function isSymbol (value : any ): boolean
Checks if a value is a symbol.
Parameters
Name Type Description valueany The value to check.
Returns
Type Name Description boolean is_symbolReturns true if the value is a symbol, otherwise false.
function isTable (value : any ): boolean
Checks whether the value is a table.
Parameters
Name Type Description valueany The value to check.
Returns
Type Name Description boolean is_tabletrue if the value is a table, false otherwise.
function isThread (value : any ): boolean
Checks whether the value type is a thread.
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_thread
function isType (object : any , value : any ): boolean
Checks if the value is an instance of the given parent.
Parameters
Name Type Description objectany The object to check for being an instance of the given parent. valueany The parent class/metatable to check against.
Returns
Type Name Description boolean is_instancetrue if object is an instance of the given parent class/metatable, false otherwise.
function isURL (value : any ): boolean
Checks if the given value is a URL .
Parameters
Name Type Description valueany The value to check.
Returns
Type Name Description boolean resultReturns true if the value is a URL , otherwise false.
function isURLSearchParams (value : any ): boolean
Parameters
Name Type Description valueany The value to check.
Returns
Type Name Description boolean resultReturns true if the value is a URL.SearchParams , otherwise false.
function isValid (value : any ): boolean
Checks if the value is valid.
Parameters
Name Type Description valueany The value to check for validity.
Returns
Type Name Description boolean is_validtrue if object is still valid and should be kept alive, false otherwise.
function isVector2 (value : any ): boolean
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_vector2
function isVector3 (value : any ): boolean
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_vector3
function isVMatrix (value : any ): boolean
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_vmatrix
function isXMLNode (value : any ): boolean
Checks whether the value type is a XMLNode .
Parameters
Name Type Description valueany
Returns
Type Name Description boolean is_xml_node
function junction (... : integer ): function
Creates a function that accepts a variable number of arguments and returns them in the order of the specified indices.
junction(...) callfjn(...) callresult ... junction(1)(A, B, C)Ajunction(2)(A, B, C)Bjunction(3)(A, B, C)Cjunction(2, 1)(A, B, C)B, Ajunction(3, 1, 2)(X, Y, Z)Z, X, Y
Parameters
Name Type Description ...integer The indices of arguments to return.
Returns
Type Name Description function fjnThe created junction function.
function knext (tbl : table <K, V>, key : K | nil ): K, V
Returns the next non-integer key–value pair in the table tbl.
Integer keys (the array part) are skipped; only hash/map keys are yielded.
Parameters
Name Type Description tbltable <K, V>keyK | nil
Returns
function kpairs (tbl : table <K, V>): (fun ( table : table <K, V>, key: ( K | nil ) ): K), V, table <K, V>
Returns two values (an iterator function and the table tbl) so that the construction
lua Copy
local t = { "a" , "b" , foo = 1 , bar = 2 }
for k, v in kpairs ( t ) do
print ( k, v )
end
-- foo 1
-- bar 2 will iterate over the non-integer key–value pairs of table t (the hash/map part).
Integer keys are skipped; use ipairs for the array part.
Parameters
Name Type Description tbltable <K, V>
Returns
Type Name Description fun ( table : table <K, V>, key: ( K | nil ) ): KVtable <K, V>
function len (value : any ): number
Returns the length of the given value.
Parameters
Name Type Description valueany The value to get the length of.
Returns
Type Name Description number lengthThe length of the given value.
function lessEqual (a : any , b : any ): boolean
Compares two values, returning whether the first is less than or equal to the second.
Unlike Lua's <= operator, this function invokes the __le metamethod from either operand if one is available. If neither operand defines __le, it falls back to the built-in less-than-or-equal operator.
Parameters
Name Type Description aany The first value to compare. bany The second value to compare.
Returns
Type Name Description boolean is_less_equaltrue if a is less than or equal to b; otherwise false.
function lessThan (a : any , b : any ): boolean
Compares two values, returning whether the first is less than the second.
Unlike Lua's < operator, this function invokes the __lt metamethod from either operand if one is available. If neither operand defines __lt, it falls back to the built-in less-than operator.
Parameters
Name Type Description aany The first value to compare. bany The second value to compare.
Returns
Type Name Description boolean is_less_thantrue if a is less than b; otherwise false.
function loadbinary (name : string ): boolean
Loads a binary module if available.
Parameters
Name Type Description namestring The binary module name, for example: "chttp".
Returns
Type Name Description boolean successtrue if binary module is successfully installed, false otherwise.
function loadbytecode (bytecode : string , env : table | nil ): function
Loads a string as a bytecode chunk in the specified environment and returns function as a compile result.
Parameters
Name Type Description bytecodestring The luajit bytecode chunk. envtable | nil The environment of compiled function.
Returns
Type Name Description function fnThe compiled function.
function loadfile (file_path : string , env : table | nil ): function
Loads a file as a lua code chunk in the specified environment and returns function as a compile result.
Parameters
Name Type Description file_pathstring The path to the file to read. envtable | nil The environment of compiled function.
Returns
Type Name Description function fnThe compiled function.
function loadstring (lua_code : string , chunk_name : string | nil , env : table | nil ): function
Loads a string as a lua code chunk in the specified environment and returns new function as a compile result.
Parameters
Name Type Description lua_codestring The lua code chunk. chunk_namestring | nil The lua code chunk name. envtable | nil The environment of compiled function.
Returns
Type Name Description function fnThe compiled function.
function lookupbinary (name : string ): boolean , string
Checks if a binary module is available and can be loaded.
Parameters
Name Type Description namestring The binary module name.
Returns
Type Name Description boolean installedtrue if binary module is available, false otherwise.string abs_pathThe absolute path to binary module.
function next (tbl : table <K, V>, key : K | nil ): K, V
If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.
Otherwise, returns three values: the next function, the table t, and nil, so that the construction
lua Copy
for k,v in pairs (t) do body end will iterate over all key–value pairs of table t.
See function next for the caveats of modifying the table during its traversal.
Parameters
Name Type Description tbltable <K, V>keyK | nil
Returns
function overload (main_fn : F, match : string[] | string , overload_fn : function ): F
Wraps main_fn so that calls whose arguments match a specific type signature are routed to overload_fn instead, while every other call falls through to main_fn unchanged.
match describes the signature to intercept, as the exact list of Lua type names (as returned by type, e.g. "string", "number", "table") the arguments must have, in order. A call goes to overload_fn only if the number of arguments equals the number of entries in match and every argument's type matches its entry; any extra or missing arguments, or any type mismatch, calls main_fn instead. Trailing nil arguments count toward the argument total, and are matched as "nil".
A single type may be given as a bare string rather than a one-element array. An empty match array has nothing to intercept, so main_fn is returned as-is without wrapping.
lua Copy
local describe = overload (
function ( ... ) return "generic" end ,
{ "string" , "number" },
function ( str, num ) return "string + number" end
)
describe ( "a" , 1 ) --> "string + number" (types and count match: overload_fn)
describe ( "a" ) --> "generic" (argument count differs: main_fn)
describe ( 1 , "a" ) --> "generic" (order matters, types differ: main_fn)
Parameters
Name Type Description main_fnFThe default function, called for any arguments that don't match match. matchstring[] | string The Lua type name (or ordered list of type names) the arguments must have for overload_fn to be used. overload_fnfunction The function called instead of main_fn when the arguments match match.
Returns
Type Name Description Foverloaded_fnA function that dispatches to overload_fn or main_fn depending on its arguments. If match is an empty array, this is main_fn itself.
function pairs (t : table <K, V>): (fun ( table : table <K, V>, index: ( K | nil ) ): K), V, table <K, V>
If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.
Otherwise, returns three values: the next function, the table t, and nil, so that the construction
lua Copy
for k,v in pairs (t) do body end will iterate over all key–value pairs of table t.
See function next for the caveats of modifying the table during its traversal.
View documents
Parameters
Name Type Description ttable <K, V>
Returns
Type Name Description fun ( table : table <K, V>, index: ( K | nil ) ): KVtable <K, V>
function print (... : any )
Prints the given arguments to the console.
Parameters
Name Type Description ...any The arguments to print.
function printDiff (a : string , b : string , minimal? : boolean )
Prints the difference between two strings to the console.
The difference is computed with string.diff and printed inline as a single colored line, terminated with a newline:
unchanged parts are printed in gray; parts inserted in b are printed in green; parts removed from a are printed in red.
Parameters
Name Type Description astring The source string. bstring The target string. minimaloptional boolean If true, prints the raw minimal edit script without the readability cleanup. Defaults to false.
function printf (fmt : string , ... : any )
Prints a formatted string to the console.
Basically the same as print( string.format( fmt, ... ) )
Parameters
Name Type Description fmtstring The format string. ...any The arguments to format/interpolate.
function printTable (tbl : table , max_depth : integer | nil )
Prints the contents of a table to the engine console as a colorized, indented, pseudo-Lua literal, recursing into any nested tables.
String keys are printed as escaped bare keys, non-string keys are printed as [ key ], and values are rendered with represent.
Nested tables are expanded as { ... } blocks and indented one level deeper for each level of nesting; if a nested table has already been visited higher up the current branch (a cycle back to an ancestor, including tbl itself), it is printed inline followed by a -- RECURSION comment instead of being expanded again.
If expanding a nested table would exceed max_depth, it is likewise printed inline followed by a -- TOO DEEP comment instead of being walked further.
Parameters
Name Type Description tbltable The table to print the contents of. max_depthinteger | nil The maximum depth of nested tables to recurse into. Defaults to 8.
function range (from : integer , to : integer , step? : integer ): (fun ( break_point: integer , index: integer ): integer | nil ), integer , integer
Creates a stateless numeric for-loop iterator that steps from from to to (inclusive), incrementing (or decrementing) by step each iteration.
Intended to be used directly in a generic for loop, e.g. for i in range( 1, 10, 2 ) do ... end.
Parameters
Name Type Description frominteger The starting value of the range. tointeger The ending value of the range (inclusive). stepoptional integer The amount to step by each iteration. Defaults to 1. Can be negative to count down.
Returns
Type Name Description fun ( break_point: integer , index: integer ): integer | nil iteratorThe iterator function to be used with a generic for loop. integer toThe final value, passed through as the loop's invariant state. integer startThe initial value, passed to the iterator on the first call.
function represent (value : any ): string
Returns a string representation of the given value.
Parameters
Name Type Description valueany The value to get the string representation of.
Returns
Type Name Description string strThe string representation of the given value.
function require (modname : string , ... : any ): ...
Loads the given module, returns any value returned by the searcher(true when nil). Besides that value, also returns as a second result the loader data returned by the searcher, which indicates how require found the module. (For instance, if the module came from a file, this loader data is the file path.)
View documents
Parameters
Name Type Description modnamestring ...any
Returns
function setfenv (location : integer | F, env : table ): F
Sets the environment of the specified function.
Parameters
Name Type Description locationinteger | FCan be a Lua function or a number that specifies the function at that stack level. envtable The environment table to set.
Returns
Type Name Description FlocationThe function with the updated environment.
function setInterval (fn : function , delay? : number , ... : any ): integer
Calls the fn function every delay seconds, until the interval is cancelled with clearInterval.
Usage example:
lua Copy
local interval_id = setInterval ( function ()
print ( "Hello, world!" )
end , 1 ) -- Calls the function every second.
setTimeout ( function ()
clearInterval ( interval_id )
end , 5 ) -- Stops it after 5 seconds.
Parameters
Name Type Description fnfunction The callback function. delayoptional number The delay between calls in seconds, default is 1. ...any Additional arguments to pass to the callback function.
Returns
Type Name Description integer interval_idThe identifier of the interval, used to cancel it with clearInterval.
function setTimeout (fn : function , delay? : number , ... : any ): integer
Calls the fn function after delay seconds.
Usage example:
lua Copy
setTimeout ( function ()
print ( "Hello, world!" )
end , 5 ) -- Calls the function after 5 seconds.
Parameters
Name Type Description fnfunction The callback function. delayoptional number The delay in seconds, default is 0. ...any Additional arguments to pass to the callback function.
Returns
Type Name Description integer timeout_idThe identifier of the timeout, used to cancel it with clearTimeout.
function sizeof (value : any , as_bytes? : boolean ): integer | nil
Returns binary size of the value as integer of bit/bytes.
Parameters
Name Type Description valueany The value to get the size of. as_bytesoptional boolean Whether return size as bytes. By default: false
Returns
Type Name Description integer | nil sizeThe size of the value.
function sleep (seconds : number )
Puts current thread to sleep for given amount of seconds.
CAUTION : This function could pause the main thread.
Parameters
Name Type Description secondsnumber
See also
function Symbol (name : string ): Symbol
Gets or creates the symbol with the given name.
Symbols are interned: calling this repeatedly with the same name returns the same object as long as it is still referenced somewhere.
Parameters
Name Type Description namestring The name of the symbol, also used in its string representation.
Returns
Type Name Description Symbol objThe symbol associated with the name.
function toBigFixed (value : any , scale? : integer ): BigFixed
Creates a BigFixed object from the given value.
If value is already a BigFixed at the requested scale, it is returned unchanged.
Parameters
Name Type Description valueany The value to convert to a BigFixed . scaleoptional integer The number of fractional digits to keep. Defaults to BigFixed.DEFAULT_SCALE .
Returns
function toBigInt (value : any , base? : integer ): BigInteger
Alias of toBigInteger.
Creates a BigInteger object from the given value.
If value is already a BigInteger , it is returned unchanged.
Parameters
Name Type Description valueany The value to convert to a BigInteger . baseoptional integer The numeric base used when parsing string values. Must be between 2 and 36 (inclusive). Defaults to 10.
Returns
function toBigInteger (value : any , base? : integer ): BigInteger
Creates a BigInteger object from the given value.
If value is already a BigInteger , it is returned unchanged.
Parameters
Name Type Description valueany The value to convert to a BigInteger . baseoptional integer The numeric base used when parsing string values. Must be between 2 and 36 (inclusive). Defaults to 10.
Returns
function tobool (e : any ): boolean | nil
Alias of toboolean.
If e has a metamethod __toboolean, calls it with e as argument and returns its result.
Otherwise, returns nil.
Parameters
Name Type Description eany The value to convert to a boolean.
Returns
Type Name Description boolean | nil boolThe boolean value of e, or nil if e cannot be converted to a boolean.
function toboolean (e : any ): boolean | nil
If e has a metamethod __toboolean, calls it with e as argument and returns its result.
Otherwise, returns nil.
Parameters
Name Type Description eany The value to convert to a boolean.
Returns
Type Name Description boolean | nil boolThe boolean value of e, or nil if e cannot be converted to a boolean.
function tocolor (value : any ): Color | nil
If value has a metamethod __tocolor, calls it with value as argument and returns its result.
Otherwise, returns nil.
Parameters
Name Type Description valueany The value to convert to a color.
Returns
Type Name Description Color | nil clrThe color value of value, or nil if value cannot be converted to a color.
function toError (error_value : any , error_class? : ErrorClass ): Error
Converts any error value into an Error and captures its call stack if it has none yet.
Can be passed to xpcall directly as a message handler.
Parameters
Name Type Description error_valueany The error value to convert. error_classoptional ErrorClass The class used to wrap values that are not errors, called with the message only. Defaults to RuntimeError .
Returns
Type Name Description Error error_object
function tohex (value : any , desired_length? : integer ): string
Returns a hexadecimal string identifying the given value.
If value's metatable defines a __hash metamethod, that function is called on value and its integer result is formatted as hex. Otherwise the value's raw memory address is used (via %p), which is stable for the lifetime of the value but has no meaning beyond identifying it — this is mainly useful for tables, functions, threads, and userdata.
If desired_length is given, the resulting string is padded with leading zeros to reach that length, or truncated from the left if it's already longer.
Parameters
Name Type Description valueany The value to get a hexadecimal identifier for. desired_lengthoptional integer The exact length the returned string should be. If omitted, the natural length is used.
Returns
Type Name Description string hex_strThe hexadecimal identifier of value, optionally padded or truncated to desired_length.
function tonumber (e : any , base? : numberbase): number | nil
If e has a metamethod __tonumber, calls it with e and base as arguments and returns its result.
When called with no base, tonumber tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns fail.
The conversion of strings can result in integers or floats, according to the lexical conventions of Lua (see §3.1). The string may have leading and trailing spaces and a sign.
View documents
Parameters
Name Type Description eany The value to convert to a number. baseoptional numberbaseThe number base, default is 10.
Returns
Type Name Description number | nil xThe number value of e, or nil if e cannot be converted to a number.
function tostring (value : any ): string
Receives a value of any type and converts it to a string in a human-readable format.
If the metatable of v has a __tostring field, then tostring calls the corresponding value with v as argument, and uses the result of the call as its result.
Otherwise, if the metatable of v has a __name field with a string value, tostring may use that string in its final result.
For complete control of how numbers are converted, use string.format .
View documents
Parameters
Name Type Description valueany The value to convert to a string.
Returns
Type Name Description string strThe string representation of value.
function try (fn : function , ... : any ): boolean , any
Calls the function in protected mode, converting a raised error into an Error .
Unlike pcall, the error value is always an Error with the call stack of the place it was raised, signals like ACTION_CANCEL are converted too, use xpcall with dreamwork.exceptions.catch to keep them.
Parameters
Name Type Description fnfunction The function to call. ...any The arguments to pass to the function.
Returns
Type Name Description boolean successtrue if the function did not raise an error.any ...The function results on success, the Error otherwise.
function type (value : any ): type
Returns a string representing the name of the type of the passed object.
Parameters
Name Type Description valueany The value to get the type of.
Returns
Type Name Description typetype_nameThe type name of the given value.
function warn (value? : any , stack_level? : integer ): Error
Displays the error with its call stack without throwing it, the current code keeps running.
Parameters
Name Type Description valueoptional any The error value to display. stack_leveloptional integer The stack level the error is blamed on.
Returns
Type Name Description Error error_objectThe displayed error.
async function yield (... : any ): ...
Yields given arguments to the apairs listener.
Parameters
Name Type Description ...any Values to yield to the listener.
Returns
Type Name Description ...anyValues passed back to this coroutine via ACTION_RESUME.
See also