ReferenceClosures

clonefunction

Makes a copy of a function that is a different value but behaves the same.

Syntax

clonefunction(func: function) -> function

Also available as

clonefuncclone_function

Parameters

ParameterTypeDescription
funcfunctionThe function to copy.

Returns

TypeDescription
functionA new function with the same code and the same environment.

Description

For a Luau function the copy shares the original's bytecode, environment and upvalues, so it computes exactly what the original does. For a C function the copy calls the same native code with the same upvalues. The copy is not equal to the original with ==, and hooking the original with hookfunction does not change the copy, which makes it useful for keeping a safe reference before you hook.

Example

local function greet(name)
    return "hello " .. name
end

local copy = clonefunction(greet)
print(copy == greet)
print(copy("apex"))

hookfunction(greet, function() return "hooked" end)
print(greet("apex"), copy("apex"))

These are Game executor contracts. Check build requirements and session lifetimes before using them.