target so that every call to it runs hook instead. Returns a
callable that invokes the original behavior, so your hook can still reach what
it replaced. Also registered as hookfunc and replaceclosure.
Parameters
function
required
The function to redirect. Both C and Luau closures can be hooked.
function
required
The replacement. It receives the same arguments the caller passed to
target.Filter
An optional filter. When given,
hook runs only for calls
the filter matches; every other call goes straight to the original. The filter
is evaluated natively, so non-matching calls never enter Luau.Returns
function
A function that calls the original, pre-hook behavior of
target. Keep this to
call through from inside your hook.Behavior
- Call through the return value, not
target. After hooking, callingtargetruns your hook. To reach the original, call the functionhookfunctionreturned. - Mismatched closure kinds are handled. Hooking across the C/Luau boundary is
supported; you do not need
targetandhookto be the same kind. - Idempotent bookkeeping. A hooked function is tracked, so
isfunctionhookedreports it andrestorefunctioncan undo it.
hookfunction(target) with
only a function and no replacement restores a function that’s currently hooked,
exactly like restorefunction(target). Call it on a
function that isn’t hooked and it raises function expected.
Example
Replace a function and still call the original:restorefunction(print) puts the
original back.
Errors
Filtering calls
Pass a filter to run the hook only for the calls you care about. Here the hook fires only when the first argument is the string"Kick":
getfilter to build a filtered function without hooking.
Related
restorefunction: undo the hook.isfunctionhooked: check hook state.hookmetamethod: hook a metamethod specifically.