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.

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