clonefunction
Creates a deep copy of a Luau function with shared upvalues.
function clonefunction(func: function): functionSynopsis
How it works
Allocates a new
LClosure (or CClosure) that shares the same Proto* pointer and upvalueUpvalueA variable captured from an enclosing scope. When a function references a local variable from an outer function, that variable becomes an upvalue — stored in an UpVal struct that persists even after the outer function returns. references as the original. The clone is a distinct object in the GC but executes identical bytecodeBytecodeThe compiled binary representation of Luau source code. A sequence of 32-bit instructions (opcodes + operands) stored in a Proto's code[] array. Executed by the Luau VM interpreter. and sees identical upvalues. Changes to upvalues via debug.setupvalue affect both the original and the clone.VM internals
For Luau closures: the clone gets its own
LClosure allocation but the p (proto) and upvals[] pointers are copied by reference, not deep-cloned. This means the clone shares upvalueUpvalueA variable captured from an enclosing scope. When a function references a local variable from an outer function, that variable becomes an upvalue — stored in an UpVal struct that persists even after the outer function returns. slots with the original — both read/write the same UpVal objects.Use case
The primary use is preserving a reference to a function's original behavior before hooking it — unlike
hookfunction's trampolineTrampolineA wrapper function that bounces (redirects) calls to another function. In executor context, newcclosure creates a C closure trampoline that calls the Luau function stored in its first upvalue., clonefunction creates a reference that remains valid even if the original is hooked again later.Usage
Clone before hooking
local original = clonefunction(print)
hookfunction(print, function(...)
original("[Hooked]", ...)
end)Parameters
func function The Luau function to clone.
Returns
function A new function object pointing to the same Luau proto as the original.