Further explanation of hook.Add

Title says it all, I would like an example of how to use a simple hook, and exactly what hook.Add does. Thanks =]

[lua]hook.Add(“PlayerDeath” , “This is called when a guy dies” , function(victim , weapon , killer)
print(killer:Nick()… " killed “…victim:Nick()…” with weapon "…weapon:GetClass())
end )

Basically, when a player dies, the engine calls the PlayerDeath hook, then the gamemode PlayerDeath function.

So that is how the DarkRP servers would call the NLR Derma menu upon death…I’m guessing?

Mixture of that and usermessages, as PlayerDeath is a serverside hook. So you use usermessages to send the info to the client.

Ah, thanks.

hook.Add(“SV-Sided hook here”, “name of hook”, function that you want here
Would that be a basic example of a correct hook?

Yeah that’s correct, except for the missing parentesis at the end.

if ( CLIENT ) then
local bla = vgui.Create(“DFrame”)
– bla bla bla

usermessage.Hook("NLR", function()
end )


if ( SERVER ) then
hook.Add(“PlayerDeath”, “NLR”, function( ply )
umsg.Start(“NLR”, ply )
end )

But sometimes remaking the frame each time is better but it depends on what your doing

He wants a new-life-rule button, so I’d assume that the contents will stay the same.

More often than not, setting visibility is better. Since you don’t want to have to recreate a 400 line panel every time someone opens / closes a menu. Especially if it has spawnicons or HTML panels on it.

I didn’t want a NLR message, just using that as an example, but thanks to all who posted on this thread :), but one more question, when is it appropriate to use a hook, only when you need the server to execute a command on it’s own?

Hooks are clientside too…


http://wiki.garrysmod.com/favicon.ico](http://wiki.garrysmod.com/?title=Hook.Add)** seems to answer many if not all of your questions…

Theres even examples! :psyboom: Something that you asked for in your OP.


Ok, but I did look at wiki, but the explanations weren’t nearly as helpful as what users posted.

I updated the explanation on the Gamemode Hooks page so it actually introduces them in a sensible fashion. Tell me what y’all think.


Great! :slight_smile: a lot better then what was there before.