Garry's Mod Wiki

hook.Add

hook.Add( string eventName, any identifier, function func )

Description

Add a hook to be called upon the given event occurring.

Arguments

1 string eventName
The event to hook on to, see and
2 any identifier
The unique identifier, usually a string. This can be used elsewhere in the code to replace or remove the hook. The identifier should be unique so that you do not accidentally override some other mods hook, unless that's what you are trying to do.

The identifier can be either a string, or a table/object with an IsValid function defined such as an Entity or Panel. numbers and booleans, for example, are not allowed.

If the identifier is a table/object, it will be inserted in front of the other arguments in the callback and the hook will be called as long as it's valid. However, as soon as IsValid( identifier ) returns false, the hook will be removed.

3 function func
The function to be called, arguments given to it depend on the .

Returning any value besides nil from the hook's function will stop other hooks of the same event down the loop from being executed. Only return a value when absolutely necessary and when you know what you are doing.

It WILL break other addons.

Example

This will hook onto the "Think" event with the function onThink, printing to the console whenever the event occurs.

local function onThink() print( "onThink has been called" ) end hook.Add( "Think", "Some unique name", onThink )
Output: "onThink has been called" repeating continuously.

Example

This works the same as above, but defines the function inside hook.Add rather than above it.

hook.Add( "Think", "Another unique name", function() print( "Think has been called" ) end )
Output: "Think has been called" repeating continuously.

Example

This code demonstrates how you can add a table function with a 'self' argument, without the use of a wrapper function

local myTable = {} function myTable:IsValid() return true end function myTable:PlayerInitialSpawn(ply) print( "CustomHook", self, ply ) end hook.Add( "CustomHook" , myTable , myTable.PlayerInitialSpawn ) hook.Run( "CustomHook" )
Output: "CustomHook table: 0x00000000 Player [1][PotatoMan]"

Page Links


Special Pages


Wikis

?

Render Time: 43ms

Session 0
DB GetPage 4
Generate Html 17
SaveChanges 8
Render Body 0
Render Sidebar 11