> ## Documentation Index
> Fetch the complete documentation index at: https://docsuncv2.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# hookfunction

Replaces `target` with `hook` and returns the original `target` function, so the original behavior is still callable.

```luau theme={null}
hookfunction(target: function, hook: function): function
```

Once hooked, every call to `target` runs `hook` instead.

Most commonly used to intercept a function (i.e. `print`), or wrap its calls without losing access to the original.

Closure types may differ between `target` and `hook` - Luau-to-Luau, C-to-C, or any cross-direction.

`newcclosure`-wrapped targets work, and the hook can carry a different upvalue count from the target.

## Parameters

Both arguments are required, otherwise - errors.

| Parameter | Type       | Description                                                                           |
| --------- | ---------- | ------------------------------------------------------------------------------------- |
| `target`  | `function` | The function to replace. Lclosure, cclosure, or `newcclosure`-wrapped - all accepted. |
| `hook`    | `function` | The function that runs in `target`'s place.                                           |

## Returns

`function` - original `target` function, **before** the hook was applied. Use it from inside `hook` to trigger pre-hook behavior - `return original(...)`.

Handles don't go stale on re-hook. Hook `target` a second time and the earlier handle still calls the body that was live when you first got it back.

## Aliases

* `hookfunc`
* `replaceclosure`

## Example

You want to mirror every call to a game function into your own pipeline - logs, counters, side-channel events. Hook the function so your code fires first, then defer to the original.

<CodeGroup>
  ```luau Example 1 theme={null}
  <<<<<<< HEAD
  local oldPrint = hookfunction(print, function(...)
      return oldPrint(...)
  end)
  =======
  -- hookfunction(target: function, hook: function): function
  >>>>>>> 50e30f53759b0538759af25c9b271514aa2c9290
  ```

  ```luau Example 2 theme={null}
  local Old
  Old = hookfunction(StockUpdated, function(tbl, x, ...)
      Events.StockUpdate(tbl)

      return Old(tbl, x, ...)
  end)
  ```
</CodeGroup>

<Tip>
  Always call the **returned handle** from inside your hook, not the target's original name. Calling `StockUpdated(...)` inside the hook re-enters the hook and recurses until the script crashes. `Old(...)` skips the hook and calls the pre-hook body.
</Tip>
