dreamworkAPI
Ctrl K
GitHub
environmentDocs / Globals

Globals

globals

Global functions and values of the dreamwork environment.

Constants

NameTypeDescription
_Gsharedmenu_GThe global environment of Lua.
_RtableThe registry of Lua.
LUA_VERSIONintegerThe version of the Lua interpreter.
GAME_VERSIONintegerContains the version number of the Garrys Mod. For example: 201211 = 01.01.2012
GAME_BRANCH"x86-64" | "dev" | "prerelease" | "unknown" | stringThe 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_MENUbooleantrue if code is running on the menu, false otherwise.
LUA_CLIENTbooleantrue if code is running on the client, false otherwise.
LUA_CLIENT_MENUbooleantrue if code is running on the client or menu, false otherwise.
LUA_CLIENT_SERVERbooleantrue if code is running on the client or server, false otherwise.
LUA_SERVERbooleantrue if code is running on the server, false otherwise.
DEVELOPERintegerA cached value of developer console variable.
FRAME_TIMEnumberThe time it takes to run one frame in seconds. Client-only
FPSnumberThe number of frames per second. Client-only
TICK_TIMEnumberThe measured time between ticks in seconds, averaged over half a second, the menu imitates a tick every frame.
TPSnumberThe measured number of ticks per second, averaged over half a second, the menu imitates a tick every frame.
nullnullA sentinel symbol that represents an explicit "no value", compare it by identity.
SYSTEM_OSXbooleantrue if the game is running on OSX.
SYSTEM_LINUXbooleantrue if the game is running on Linux.
SYSTEM_WINDOWSbooleantrue if the game is running on Windows.
SYSTEM_X64booleantrue if the game is running on 64-bit architecture.
SYSTEM_X32booleantrue 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_COUNTRYstringThe country code of the operating system. (ISO 3166-1 alpha-2)
SYSTEM_HAS_BATTERYbooleantrue 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.
import
inextReturns 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…
isAngle3
isBigFixedChecks 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.
isQuaternion
isStringChecks 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.
isVector2
isVector3
isVMatrix
isXMLNodeChecks 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.

#apairs

sharedmenuasyncnodiscardsource
async function apairs(iterator: async, ...: any): async, thread

Iterates over async iterator, calling it with given arguments.

Example

lua
---@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
NameTypeDescription
iteratorasyncfun(...): futures.AsyncIterator<K, V> The async iterator function to drive.
...anyArguments to pass to iterator.
Returns
TypeNameDescription
asyncfun(...): K, V
thread
See also

#assert

sharedmenusource
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
local file = assert( open( path ), "cannot open '%s'", path )
assert( size >= 0, ValueError, "size must be positive, got %d", size )
Parameters
NameTypeDescription
valueTThe value to check.
messageoptional( string | Error | ErrorClass )?The error message, error object or error class.
...anyThe message format arguments.
Returns
TypeNameDescription
Tvalue
any...

#checktype

sharedmenusource
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
NameTypeDescription
indexintegerThe stack index of the local variable to check (as used by debug.getlocal).
...anyThe expected type names (strings) or class/type tables (with an optional __type field) to check the value against.

#checkvalue

sharedmenusource
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
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
NameTypeDescription
indexintegerThe 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.

#clearInterval

sharedmenusource
function clearInterval(interval_id: integer): boolean

Cancels an interval created by setInterval, so its callback will not be called anymore.

Usage example:

lua
local interval_id = setInterval( function()
    print( "Hello, world!" )
end, 1 )

clearInterval( interval_id )
Parameters
NameTypeDescription
interval_idintegerThe identifier of the interval returned by setInterval.
Returns
TypeNameDescription
booleanis_clearedReturns true if the interval was found and cancelled, otherwise false.

#clearTimeout

sharedmenusource
function clearTimeout(timeout_id: integer): boolean

Cancels a timeout created by setTimeout, so its callback will not be called.

Usage example:

lua
local timeout_id = setTimeout( function()
    print( "This will never be printed." )
end, 5 )

clearTimeout( timeout_id )
Parameters
NameTypeDescription
timeout_idintegerThe identifier of the timeout returned by setTimeout.
Returns
TypeNameDescription
booleanis_clearedReturns true if the timeout was found and cancelled, otherwise false.

#copy

sharedmenunodiscardsource
function copy(value: T): T

Returns the copy of the value.

Parameters
NameTypeDescription
valueTThe value to copy.
Returns
TypeNameDescription
TcopyThe copy of the value.

#dispatch

sharedmenunodiscardsource
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
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
NameTypeDescription
inputsOverloadInput<F>[]The signatures to dispatch between, checked in order (first match wins).
fallback_fnoptionalFThe function called when no input matches. If omitted, a non-matching call raises an error.
Returns
TypeNameDescription
Ffn_overA function that dispatches to the matching input's fn, or to fallback_fn.

#dofile

sharedmenusource
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
NameTypeDescription
file_pathstring
...any
Returns
TypeNameDescription
any...

#equal

sharedmenunodiscardsource
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
NameTypeDescription
aanyThe first value to compare.
banyThe second value to compare.
Returns
TypeNameDescription
booleanis_equaltrue if the values are considered equal; otherwise false.

#error

sharedmenusource
function error(value?: any, stack_level?: integer)

Throws an error with the specified message and level.

Parameters
NameTypeDescription
valueoptionalanyThe error value to throw.
stack_leveloptionalintegerThe stack level to throw the error.

#errorf

sharedmenusource
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
NameTypeDescription
fmtstringThe error message format.
...anyThe error message arguments to format/interpolate.

#getfenv

sharedmenunodiscardsource
function getfenv(location: integer | function): table

Returns the current environment in use by the function.

Parameters
NameTypeDescription
locationinteger | functionCan be a Lua function or a number that specifies the function at that stack level.
Returns
TypeNameDescription
tablefenvSpecified function environment.

#getmetatable

sharedmenunodiscardsource
function getmetatable(object: any): metatable | table | nil

If object does not have a metatable, returns nil.

Otherwise, if the object's metatable has a __metatable field, returns the associated value.

Otherwise, returns the metatable of the given object.

Use debug.getmetatable to get the real metatable regardless of a __metatable field.

View documents

Parameters
NameTypeDescription
objectanyThe value to get the metatable of.
Returns
TypeNameDescription
metatable | table | nilmetatableThe metatable (or its __metatable value), or nil if there is none.

#hash

sharedmenunodiscardsource
function hash(value: any): integer

Returns the hash of the given value.

Parameters
NameTypeDescription
valueanyThe value to get the hash of.
Returns
TypeNameDescription
integerhashThe hash of the given value.

#import

sharedmenusource
function import(package_name: string, package_version: string): any
Parameters
NameTypeDescription
package_namestring
package_versionstring
Returns
TypeNameDescription
any

#inext

sharedmenunodiscardsource
function inext(tbl: table, index: integer): integer | nil, any

Returns the next value in the table t, with the given index.

Parameters
NameTypeDescription
tbltable
indexinteger
Returns
TypeNameDescription
integer | nil
any

#ipairs

sharedmenunodiscardsource
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
    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
NameTypeDescription
tV[]
Returns
TypeNameDescription
fun( table: V[], i: ( integer | nil ) ): integer
V
V[]
integeri

#isAngle3

nodiscardsource
function isAngle3(value: any): boolean
Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_angle3

#isBigFixed

sharedmenunodiscardsource
function isBigFixed(value: any): boolean

Checks whether the value is a BigFixed.

Parameters
NameTypeDescription
valueanyThe value to check.
Returns
TypeNameDescription
booleanis_bigfixedtrue if the value is a BigFixed, false otherwise.

#isBigInteger

sharedmenunodiscardsource
function isBigInteger(value: any): boolean

Checks whether the value is a BigInteger.

Parameters
NameTypeDescription
valueanyThe value to check.
Returns
TypeNameDescription
booleanis_biginttrue if the value is a BigInteger, false otherwise.

#isBoolean

sharedmenunodiscardsource
function isBoolean(value: any): boolean

Checks whether the value type is boolean.

Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_bool

#isCallable

sharedmenunodiscardsource
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
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_callable

#isClass

sharedmenunodiscardsource
function isClass(value: any): boolean

Checks if the value is a class.

Parameters
NameTypeDescription
valueanyThe value to check for being a class.
Returns
TypeNameDescription
booleanis_classtrue if value is a class, false otherwise.

#isError

sharedmenunodiscardsource
function isError(value: any): boolean

Returns whether the given value is an error.

Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_error

#isFunction

sharedmenunodiscardsource
function isFunction(value: any): boolean

Checks whether the value type is a function.

Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_function

#isHTMLNode

sharedmenunodiscardsource
function isHTMLNode(value: any): boolean

Checks whether the value type is a HTMLNode.

Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_html_node

#isInstance

sharedmenunodiscardsource
function isInstance(object: any, ...: any): boolean

Checks if the value is an instance of the given parent.

Parameters
NameTypeDescription
objectanyThe object to check for being an instance of the given parent.
...anyThe parent classes/metatables to check against.
Returns
TypeNameDescription
booleanis_instancetrue if object is an instance of any of the given parent classes/metatables, false otherwise.

#isInteger

sharedmenunodiscardsource
function isInteger(value: any): boolean

Checks whether the value type is a integer.

Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_integer

#isNil

sharedmenunodiscardsource
function isNil(value: any): boolean

Checks whether the value type is nil.

Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_nil

#isNumber

sharedmenunodiscardsource
function isNumber(value: any): boolean

Checks whether the value type is a number.

Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_number

#isObject

sharedmenunodiscardsource
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
NameTypeDescription
valueanyThe value to check for being an object.
Returns
TypeNameDescription
booleanis_objecttrue if value is an object created by a class, false otherwise.

#isQuaternion

nodiscardsource
function isQuaternion(value: any): boolean
Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_quaternion

#isString

sharedmenunodiscardsource
function isString(value: any): boolean

Checks whether the value type is a string.

Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_string

#isSymbol

sharedmenunodiscardsource
function isSymbol(value: any): boolean

Checks if a value is a symbol.

Parameters
NameTypeDescription
valueanyThe value to check.
Returns
TypeNameDescription
booleanis_symbolReturns true if the value is a symbol, otherwise false.

#isTable

sharedmenunodiscardsource
function isTable(value: any): boolean

Checks whether the value is a table.

Parameters
NameTypeDescription
valueanyThe value to check.
Returns
TypeNameDescription
booleanis_tabletrue if the value is a table, false otherwise.

#isThread

sharedmenunodiscardsource
function isThread(value: any): boolean

Checks whether the value type is a thread.

Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_thread

#isType

sharedmenunodiscardsource
function isType(object: any, value: any): boolean

Checks if the value is an instance of the given parent.

Parameters
NameTypeDescription
objectanyThe object to check for being an instance of the given parent.
valueanyThe parent class/metatable to check against.
Returns
TypeNameDescription
booleanis_instancetrue if object is an instance of the given parent class/metatable, false otherwise.

#isURL

sharedmenunodiscardsource
function isURL(value: any): boolean

Checks if the given value is a URL.

Parameters
NameTypeDescription
valueanyThe value to check.
Returns
TypeNameDescription
booleanresultReturns true if the value is a URL, otherwise false.

#isURLSearchParams

sharedmenunodiscardsource
function isURLSearchParams(value: any): boolean

Checks if the given value is a URL.SearchParams.

Parameters
NameTypeDescription
valueanyThe value to check.
Returns
TypeNameDescription
booleanresultReturns true if the value is a URL.SearchParams, otherwise false.

#isValid

sharedmenunodiscardsource
function isValid(value: any): boolean

Checks if the value is valid.

Parameters
NameTypeDescription
valueanyThe value to check for validity.
Returns
TypeNameDescription
booleanis_validtrue if object is still valid and should be kept alive, false otherwise.

#isVector2

nodiscardsource
function isVector2(value: any): boolean
Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_vector2

#isVector3

nodiscardsource
function isVector3(value: any): boolean
Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_vector3

#isVMatrix

nodiscardsource
function isVMatrix(value: any): boolean
Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_vmatrix

#isXMLNode

sharedmenunodiscardsource
function isXMLNode(value: any): boolean

Checks whether the value type is a XMLNode.

Parameters
NameTypeDescription
valueany
Returns
TypeNameDescription
booleanis_xml_node

#junction

sharedmenunodiscardsource
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)A
junction(2)(A, B, C)B
junction(3)(A, B, C)C
junction(2, 1)(A, B, C)B, A
junction(3, 1, 2)(X, Y, Z)Z, X, Y
Parameters
NameTypeDescription
...integerThe indices of arguments to return.
Returns
TypeNameDescription
functionfjnThe created junction function.

#knext

sharedmenunodiscardsource
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
NameTypeDescription
tbltable<K, V>
keyK | nil
Returns
TypeNameDescription
K
V

#kpairs

sharedmenunodiscardsource
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
    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
NameTypeDescription
tbltable<K, V>
Returns
TypeNameDescription
fun( table: table<K, V>, key: ( K | nil ) ): K
V
table<K, V>

#len

sharedmenunodiscardsource
function len(value: any): number

Returns the length of the given value.

Parameters
NameTypeDescription
valueanyThe value to get the length of.
Returns
TypeNameDescription
numberlengthThe length of the given value.

#lessEqual

sharedmenunodiscardsource
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
NameTypeDescription
aanyThe first value to compare.
banyThe second value to compare.
Returns
TypeNameDescription
booleanis_less_equaltrue if a is less than or equal to b; otherwise false.

#lessThan

sharedmenunodiscardsource
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
NameTypeDescription
aanyThe first value to compare.
banyThe second value to compare.
Returns
TypeNameDescription
booleanis_less_thantrue if a is less than b; otherwise false.

#loadbinary

sharedmenusource
function loadbinary(name: string): boolean

Loads a binary module if available.

Parameters
NameTypeDescription
namestringThe binary module name, for example: "chttp".
Returns
TypeNameDescription
booleansuccesstrue if binary module is successfully installed, false otherwise.

#loadbytecode

sharedmenunodiscardsource
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
NameTypeDescription
bytecodestringThe luajit bytecode chunk.
envtable | nilThe environment of compiled function.
Returns
TypeNameDescription
functionfnThe compiled function.

#loadfile

sharedmenunodiscardsource
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
NameTypeDescription
file_pathstringThe path to the file to read.
envtable | nilThe environment of compiled function.
Returns
TypeNameDescription
functionfnThe compiled function.

#loadstring

sharedmenunodiscardsource
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
NameTypeDescription
lua_codestringThe lua code chunk.
chunk_namestring | nilThe lua code chunk name.
envtable | nilThe environment of compiled function.
Returns
TypeNameDescription
functionfnThe compiled function.

#lookupbinary

sharedmenusource
function lookupbinary(name: string): boolean, string

Checks if a binary module is available and can be loaded.

Parameters
NameTypeDescription
namestringThe binary module name.
Returns
TypeNameDescription
booleaninstalledtrue if binary module is available, false otherwise.
stringabs_pathThe absolute path to binary module.

#next

sharedmenunodiscardsource
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
    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
NameTypeDescription
tbltable<K, V>
keyK | nil
Returns
TypeNameDescription
K
V

#overload

sharedmenunodiscardsource
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
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
NameTypeDescription
main_fnFThe default function, called for any arguments that don't match match.
matchstring[] | stringThe Lua type name (or ordered list of type names) the arguments must have for overload_fn to be used.
overload_fnfunctionThe function called instead of main_fn when the arguments match match.
Returns
TypeNameDescription
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.

#pairs

sharedmenunodiscardsource
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
    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
NameTypeDescription
ttable<K, V>
Returns
TypeNameDescription
fun( table: table<K, V>, index: ( K | nil ) ): K
V
table<K, V>

#print

sharedmenusource
function print(...: any)

Prints the given arguments to the console.

Parameters
NameTypeDescription
...anyThe arguments to print.

#printDiff

sharedmenusource
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
NameTypeDescription
astringThe source string.
bstringThe target string.
minimaloptionalbooleanIf true, prints the raw minimal edit script without the readability cleanup. Defaults to false.

#printf

sharedmenusource
function printf(fmt: string, ...: any)

Prints a formatted string to the console.

Basically the same as print( string.format( fmt, ... ) )

Parameters
NameTypeDescription
fmtstringThe format string.
...anyThe arguments to format/interpolate.

#printTable

sharedmenusource
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
NameTypeDescription
tbltableThe table to print the contents of.
max_depthinteger | nilThe maximum depth of nested tables to recurse into. Defaults to 8.

#range

sharedmenunodiscardsource
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
NameTypeDescription
fromintegerThe starting value of the range.
tointegerThe ending value of the range (inclusive).
stepoptionalintegerThe amount to step by each iteration. Defaults to 1. Can be negative to count down.
Returns
TypeNameDescription
fun( break_point: integer, index: integer ): integer | niliteratorThe iterator function to be used with a generic for loop.
integertoThe final value, passed through as the loop's invariant state.
integerstartThe initial value, passed to the iterator on the first call.

#represent

sharedmenunodiscardsource
function represent(value: any): string

Returns a string representation of the given value.

Parameters
NameTypeDescription
valueanyThe value to get the string representation of.
Returns
TypeNameDescription
stringstrThe string representation of the given value.

#require

sharedmenusource
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
NameTypeDescription
modnamestring
...any
Returns
TypeNameDescription
...

#setfenv

sharedmenusource
function setfenv(location: integer | F, env: table): F

Sets the environment of the specified function.

Parameters
NameTypeDescription
locationinteger | FCan be a Lua function or a number that specifies the function at that stack level.
envtableThe environment table to set.
Returns
TypeNameDescription
FlocationThe function with the updated environment.

#setInterval

sharedmenusource
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
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
NameTypeDescription
fnfunctionThe callback function.
delayoptionalnumberThe delay between calls in seconds, default is 1.
...anyAdditional arguments to pass to the callback function.
Returns
TypeNameDescription
integerinterval_idThe identifier of the interval, used to cancel it with clearInterval.

#setTimeout

sharedmenusource
function setTimeout(fn: function, delay?: number, ...: any): integer

Calls the fn function after delay seconds.

Usage example:

lua
setTimeout( function()
    print( "Hello, world!" )
end, 5 ) -- Calls the function after 5 seconds.
Parameters
NameTypeDescription
fnfunctionThe callback function.
delayoptionalnumberThe delay in seconds, default is 0.
...anyAdditional arguments to pass to the callback function.
Returns
TypeNameDescription
integertimeout_idThe identifier of the timeout, used to cancel it with clearTimeout.

#sizeof

sharedmenunodiscardsource
function sizeof(value: any, as_bytes?: boolean): integer | nil

Returns binary size of the value as integer of bit/bytes.

Parameters
NameTypeDescription
valueanyThe value to get the size of.
as_bytesoptionalbooleanWhether return size as bytes. By default: false
Returns
TypeNameDescription
integer | nilsizeThe size of the value.

#sleep

sharedmenusource
function sleep(seconds: number)

Puts current thread to sleep for given amount of seconds.

CAUTION: This function could pause the main thread.

Parameters
NameTypeDescription
secondsnumber
See also

#Symbol

sharedmenunodiscardsource
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
NameTypeDescription
namestringThe name of the symbol, also used in its string representation.
Returns
TypeNameDescription
SymbolobjThe symbol associated with the name.

#toBigFixed

sharedmenunodiscardsource
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
NameTypeDescription
valueanyThe value to convert to a BigFixed.
scaleoptionalintegerThe number of fractional digits to keep. Defaults to BigFixed.DEFAULT_SCALE.
Returns
TypeNameDescription
BigFixedobj

#toBigInt

sharedmenunodiscardsource
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
NameTypeDescription
valueanyThe value to convert to a BigInteger.
baseoptionalintegerThe numeric base used when parsing string values. Must be between 2 and 36 (inclusive). Defaults to 10.
Returns
TypeNameDescription
BigIntegerobj

#toBigInteger

sharedmenunodiscardsource
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
NameTypeDescription
valueanyThe value to convert to a BigInteger.
baseoptionalintegerThe numeric base used when parsing string values. Must be between 2 and 36 (inclusive). Defaults to 10.
Returns
TypeNameDescription
BigIntegerobj

#tobool

sharedmenunodiscardsource
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
NameTypeDescription
eanyThe value to convert to a boolean.
Returns
TypeNameDescription
boolean | nilboolThe boolean value of e, or nil if e cannot be converted to a boolean.

#toboolean

sharedmenunodiscardsource
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
NameTypeDescription
eanyThe value to convert to a boolean.
Returns
TypeNameDescription
boolean | nilboolThe boolean value of e, or nil if e cannot be converted to a boolean.

#tocolor

sharedmenunodiscardsource
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
NameTypeDescription
valueanyThe value to convert to a color.
Returns
TypeNameDescription
Color | nilclrThe color value of value, or nil if value cannot be converted to a color.

#toError

sharedmenunodiscardsource
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
NameTypeDescription
error_valueanyThe error value to convert.
error_classoptionalErrorClassThe class used to wrap values that are not errors, called with the message only. Defaults to RuntimeError.
Returns
TypeNameDescription
Errorerror_object

#tohex

sharedmenunodiscardsource
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
NameTypeDescription
valueanyThe value to get a hexadecimal identifier for.
desired_lengthoptionalintegerThe exact length the returned string should be. If omitted, the natural length is used.
Returns
TypeNameDescription
stringhex_strThe hexadecimal identifier of value, optionally padded or truncated to desired_length.

#tonumber

sharedmenunodiscardsource
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
NameTypeDescription
eanyThe value to convert to a number.
baseoptionalnumberbaseThe number base, default is 10.
Returns
TypeNameDescription
number | nilxThe number value of e, or nil if e cannot be converted to a number.

#tostring

sharedmenunodiscardsource
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
NameTypeDescription
valueanyThe value to convert to a string.
Returns
TypeNameDescription
stringstrThe string representation of value.

#try

sharedmenusource
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
NameTypeDescription
fnfunctionThe function to call.
...anyThe arguments to pass to the function.
Returns
TypeNameDescription
booleansuccesstrue if the function did not raise an error.
any...The function results on success, the Error otherwise.

#type

sharedmenunodiscardsource
function type(value: any): type

Returns a string representing the name of the type of the passed object.

Parameters
NameTypeDescription
valueanyThe value to get the type of.
Returns
TypeNameDescription
typetype_nameThe type name of the given value.

#warn

sharedmenusource
function warn(value?: any, stack_level?: integer): Error

Displays the error with its call stack without throwing it, the current code keeps running.

Parameters
NameTypeDescription
valueoptionalanyThe error value to display.
stack_leveloptionalintegerThe stack level the error is blamed on.
Returns
TypeNameDescription
Errorerror_objectThe displayed error.

#yield

sharedmenuasyncsource
async function yield(...: any): ...

Yields given arguments to the apairs listener.

Parameters
NameTypeDescription
...anyValues to yield to the listener.
Returns
TypeNameDescription
...anyValues passed back to this coroutine via ACTION_RESUME.
See also
Generated from the dreamwork meta branch.