Redirects 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, calling target runs your hook. To reach the original, call the function hookfunction returned.
  • Mismatched closure kinds are handled. Hooking across the C/Luau boundary is supported; you do not need target and hook to be the same kind.
  • Idempotent bookkeeping. A hooked function is tracked, so isfunctionhooked reports it and restorefunction can undo it.
There’s also a single-argument restore form. Calling 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:
When you’re done, 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":
Every other call bypasses the hook entirely. See Filter for the available filters and getfilter to build a filtered function without hooking.