Hook Library Usage
What is the hook library?
The hook library allows scripts to interact with game or user created events. It allows you to "hook" a function onto an event created with hook.Run or hook.Call and run code when that events happens that either works independently or modifies the event's arguments. This is the preferred method instead of overriding functions to add your own code into it.
Using the hook library
Adding hooks
To add a hook you use the hook.Add function. This function takes the following arguments:
- Event Name - This is the name of the event to run your hook on.
- Hook ID - This is an identifier unique to the hook you are adding and can be used to remove the hook later.
- Hook Function - This is the function that is ran upon the event.
Below is an example of adding a hook to print to the console whenever a player spawns:
It can also be written this way
This will print "{PlayerName} has spawned!" in to the console whenever a player spawns.
Hook functions
When a hook is called, it is given arguments specific to its event. Information for each hook can be found on this wiki at and . Some hooks will be given no arguments at all.
Gamemodes and hooks
Functions under the GM (or GAMEMODE) table are also treated as hooks. When an event is being ran, all hooks defined using hook.Add are called before the Gamemode function.
This means that the following code within a gamemode will also print to the console whenever a player spawns:
Returning from hooks
When a value is returned from a hook, other hooks for the same event do not run. This means that you are able to override other hooks and gamemode functions.
return
and return false
are different.To see if the returned value of the hook will affect it the wiki page of that hook should have Returns
section.
This example shows the use of the SANDBOX:PlayerSpawnProp event. This event expects hooks to return true if the player is allowed to spawn a prop and false otherwise. If nothing is returned it'll run the next hook.
This code will only allow admins to spawn props. As it is always returning a value, it overrides other hooks.
Adding your own events
You can add your own events by simply calling hook.Run or hook.Call. You shouldn't need to create a hook for every event that happens in your addons as that would be useless but important things such as a gamemode checking for a map switch or events that you want external scripts to edit should have hooks.
The following example calls all hooks that are hooked to the "PerformMultiplication" event and supplied an argument to each hook.
This example will output 12