Garry's Mod Wiki


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


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


1 string eventName
The event to hook on to. This can be any GM hook, gameevent after using gameevent.Listen, or custom hook run with hook.Call or hook.Run.
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, if IsValid( identifier ) returns false when any eventName hook is called, the hook will be removed.

3 function func
The function to be called, arguments given to it depend on the identifier used.
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.


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.


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.


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]"