Closures

Hook, wrap, clone and inspect functions.

21 functionssUNC 100%Lynx 0.747

Closure functions let you compile source, wrap or clone functions, inspect their type and replace their behavior. Use Filters to select which calls a replacement handles.

loadstring

loadstring(source: string, chunkName: string? = "="): (function?, string?)

loadstring compiles a Luau source string into a function that you can call later. It does not run the source during compilation.

Also available as load_string.

Parameters

sourcestring
Luau source, including embedded bytes.
chunkNamestring?
Optional.Source name used in diagnostics. Default "=".

Returns

function?, string?

Compiled closure, or nil followed by the compiler diagnostic.

Example

local f, err = loadstring("return ...", "=sample")
if f then print(f(42)) else warn(err) end

hookfunction

hookfunction(target: function, replacement: function, filter: FilterBase? = nil): function

hookfunction replaces a function with another function and returns its previous behavior. Existing references to the target call the replacement.

Also available as hook_function, hookfunc, replaceclosure, replacefunction, replacefunc, detourfunction, detour_function, hook_func and replace_closure.

Parameters

targetfunction
The function whose calls will be replaced.
replacementfunction
The function to call instead of the target.
filterFilterBase?
Optional.A filter selecting which calls use the replacement. Default nil.

Returns

function

Previous callable behavior; retain it before calling the target from the replacement.

Example

local function value() return 1 end
local old = hookfunction(value, function() return 2 end)
print(value(), old())
restorefunction(value)

hookmetamethod

hookmetamethod(object: any, method: string, replacement: function, arg_guard: boolean? = true, filter: FilterBase? = nil): function

hookmetamethod replaces a named metamethod on an object and returns the previous metamethod. Values that share the same metatable also share this change.

Also available as hookmetafield, hook_meta_method, hookmetafish and hook_metamethod.

Parameters

objectany
Value whose metamethod is resolved.
methodstring
Metamethod field name.
replacementfunction
Receives the original arguments.
arg_guardboolean?
Optional.Checks the argument count and receiver type before a supported native metamethod calls the replacement. Default true.
filterFilterBase?
Optional.An additional native call filter. Calls must match both the argument guard, when active, and this filter. Default nil.

Returns

function

Previous metamethod callable.

Example

local old
old = hookmetamethod(game, "__namecall", newcclosure(function(self, ...)
return old(self, ...)
end), true, NamecallFilter.new("GetService"))
restorefunction(getrawmetatable(game).__namecall)

Metamethod argument guard

The guard counts the receiver as argument 1 and checks these minimum argument counts. Extra arguments are allowed, and an explicit nil still counts as an argument.

MetamethodMinimum arguments
__newindex3
__index, __add, __sub, __mul, __div, __idiv, __mod, __pow, __concat, __eq, __lt, __le, __band, __bor, __bxor, __shl, __shr2
__namecall, __call, __tostring, __len, __unm, __bnot, __iter, __gc1

Argument 1 must have the same Luau value type as object. Userdata must also have the same native tag and metatable. This matches a receiver's type rather than its identity or Instance class, so another compatible receiver can pass. __namecall additionally requires an active namecall method. The guard does not check property names or every argument's value; add a Filter for narrower matching. Metamethods outside the table receive no automatic guard.

restorefunction

restorefunction(target: function): ()

restorefunction removes the replacement from a function and restores its original behavior.

Also available as restore_function, restorefunc and restoreclosure.

Parameters

targetfunction
Public target function to restore.

Returns

()

No return values.

Example

local function f() return "original" end
hookfunction(f, function() return "changed" end)
restorefunction(f)
print(f())

isfunctionhooked

isfunctionhooked(fn: function): boolean

isfunctionhooked checks whether a function currently has an active replacement.

Also available as is_function_hooked and ishooked.

Parameters

fnfunction
Function to inspect.

Returns

boolean

true when an active replacement is registered for the function.

Example

local function f() end
print(isfunctionhooked(f))

newcclosure

newcclosure(fn: function, debugName: string? = nil): function

newcclosure wraps a function in a C closure. Calling the wrapper forwards the arguments to the original function and returns its results, including when the original function yields.

Also available as new_cclosure, new_c_closure and newcc.

Parameters

fnfunction
The function to wrap and call through the C closure.
debugNamestring?
Optional.Optional wrapper debug name. Default nil.

Returns

function

A new forwarding C closure.

Example

local add = newcclosure(function(a, b) return a + b end, "add")
print(add(2, 3), iscclosure(add))

newlclosure

newlclosure(fn: function, debugName: string? = "newlclosureWrapper"): function

newlclosure wraps a function in a new Luau closure that forwards its arguments and return values.

Also available as new_lclosure, new_l_closure and newlc.

Parameters

fnfunction
The function to wrap and call through the Luau closure.
debugNamestring?
Optional.Source name for the generated Luau wrapper. Default "newlclosureWrapper".

Returns

function

New Luau wrapper that forwards all arguments and results.

Example

local wrapped = newlclosure(math.abs, "absWrapper")
print(wrapped(-4), islclosure(wrapped))

wrapclosure

wrapclosure(fn: function): function | string

wrapclosure creates a wrapper with the same closure kind as the supplied function: a C wrapper for a C function, or a Luau wrapper otherwise.

Also available as wrap_closure.

Parameters

fnfunction
The function to wrap, preserving its C or Luau closure kind.

Returns

function | string

Wrapper on success; the protected constructor error value on failure.

Example

local wrapper = wrapclosure(math.abs)
if type(wrapper) == "function" then print(wrapper(-3)) end

clonefunction

clonefunction(fn: function): function

clonefunction creates a separate function object with the same behavior as the supplied function at the time of cloning.

Also available as clonefunc and clone_function.

Parameters

fnfunction
Function to clone.

Returns

function

Distinct callable snapshot.

Example

local function f(x) return x * 2 end
local copy = clonefunction(f)
print(copy(5), copy == f)

iscclosure

iscclosure(fn: function): boolean

iscclosure checks whether a function is a C closure, including a built-in function or a wrapper made by newcclosure.

Also available as is_c_closure.

Parameters

fnfunction
Function to inspect.

Returns

boolean

true for a C closure; otherwise false.

Example

print(iscclosure(math.abs))

islclosure

islclosure(fn: function): boolean

islclosure checks whether a function is a Luau closure.

Also available as is_l_closure.

Parameters

fnfunction
Function to inspect.

Returns

boolean

true for a Luau closure; otherwise false.

Example

print(islclosure(function() end))

isexecutorclosure

isexecutorclosure(fn: function): boolean

isexecutorclosure checks whether a function belongs to Lynx.

Also available as isourclosure, isXclosure, checkclosure, is_our_closure, is_executor_closure, is_krnl_closure, is_protosmasher_closure, issynapsefunction and is_synapse_function.

Parameters

fnfunction
Function to inspect.

Returns

boolean

true when the function is marked as Lynx-owned; otherwise false.

Example

print(isexecutorclosure(function() end))

isnewcclosure

isnewcclosure(fn: function): boolean

isnewcclosure checks whether a function is a newcclosure wrapper owned by the current VM.

Also available as is_new_cclosure, is_new_cc, iscustomcclosure and is_custom_cclosure.

Parameters

fnfunction
Function to inspect.

Returns

boolean

true for a recognized newcclosure wrapper in the current VM; otherwise false.

Example

local wrapped = newcclosure(function() return 42 end)
print(isnewcclosure(wrapped)) -- true

isnewlclosure

isnewlclosure(fn: function): boolean

isnewlclosure checks for the environment marker used by newlclosure wrappers.

Also available as is_new_lclosure and is_new_lc.

Parameters

fnfunction
Function to inspect.

Returns

boolean

true when the function environment contains a function-valued wrap field.

Example

print(isnewlclosure(newlclosure(math.abs)))

checkcaller

checkcaller(): boolean

checkcaller checks whether the current call is running on a Lynx-owned thread.

Also available as check_caller, is_lynx_caller, issynapsethread and check_calling_script.

Returns

boolean

true when the calling thread is marked as Lynx-owned; otherwise false.

Example

print(checkcaller())

isexecutorthread

isexecutorthread(thread: thread? = coroutine.running()): boolean

isexecutorthread checks whether a thread belongs to Lynx. If you omit the thread, it checks the calling thread.

Also available as is_executor_thread, is_executor_state and isexecutorstate.

Parameters

threadthread?
Optional.The thread to check. Omit it to check the caller. Default coroutine.running().

Returns

boolean

Whether that thread carries the module ownership mark.

Example

print(isexecutorthread(coroutine.running()))

checkcallstack

checkcallstack(level: number? = 2): boolean

checkcallstack checks whether the call chain from a chosen stack level consists of Lynx-owned functions.

Also available as check_callstack and check_call_stack.

Parameters

levelnumber?
Optional.First frame level to include. Default 2.

Returns

boolean

true when the call chain passes the ownership check; otherwise false.

Example

print(checkcallstack(2))

setstackhidden

setstackhidden(target: function | number, hidden: boolean? = true): ()

setstackhidden controls whether a function appears in the stack information returned by Lynx debug tools.

Also available as set_stack_hidden.

Parameters

targetfunction | number
The function to show or hide, or its stack level.
hiddenboolean?
Optional.Whether the function is hidden. Default true.

Returns

()

No return values.

Example

local function helper() end
setstackhidden(helper, true)
setstackhidden(helper, false)

getfunctionhash

getfunctionhash(fn: function): string

getfunctionhash returns a SHA-384 hash for a Luau or native function.

Parameters

fnfunction
Luau or native closure to hash.

Returns

string

The function digest as a 96-character hexadecimal string.

Example

local function f() return "sample" end
print(getfunctionhash(f))

getfunctionbytecode

getfunctionbytecode(fn: function): string?

getfunctionbytecode returns the compiled bytecode of a supported Luau function.

Also available as get_function_bytecode and dumpfunction.

Parameters

fnfunction
Function whose loaded prototype is serialized.

Returns

string?

Serialized bytecode, or nil.

Example

local bytes = getfunctionbytecode(function() return 42 end)
print(bytes and #bytes)

Function calls

trampoline_call

trampoline_call(callback: (...any) -> ...any, frames: {FrameSpec}, options: ThreadOptions, ...any): (boolean, ...any)

trampoline_call calls a function with a chosen thread context and stack frames, returning its success state and results.

Also available as trampolinecall.

Parameters

callback(...any) -> ...any
The function to call.
frames{FrameSpec}
The stack frames to use for the call.
optionsThreadOptions
The thread context to use for the call.
......any
Arguments passed to the callback or signal.

Returns

(boolean, ...any)

A success boolean followed by results, or false followed by an error.

FrameSpec

func
Typefunction?
Use an existing function for this frame.
currentline
Typenumber?
Integer source-line override.
env
Typetable?
Environment for a synthetic frame without func.
source
Typestring?
Synthetic source, default =trampoline_call.
name
Typestring?
Synthetic function name.
numparams
Typenumber?
Synthetic parameter count, integer 0..255.
is_vararg
Typeboolean?
Synthetic variadic flag.

ThreadOptions

thread
Typethread?
Parent thread; omitted uses the VM main thread.
script
TypeInstance?
Source-script association for the child.
identity
Typenumber?
Nonnegative integer identity. Without a parent or explicit identity the child uses 2.
env
Typetable?
Child global environment override.
local ok, value = trampoline_call(function(x)
return x * 2
end, {}, {}, 21)
print(ok, value) -- true, 42