hook.Add

From Garry's Mod
Jump to: navigation, search
 hook.Add( )

Contents

Description

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

Arguments

string eventName

The event to hook on to, see GM Hooks and Sandbox Hooks

Arguments

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.

Arguments

function func

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

WARNING 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.

Examples

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.

Examples

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.

Examples

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]"
Personal tools
Navigation