Return to Main Page

Hooks

Page white text.png Description:This is an introduction to the lua language in general and is a recommended read if you are a beginner.
link=User:Dim1xs Author:Dim1xs
Calendar.png Created:December 15th 2023

Introdution

This article will teach you the basics of a couple important concepts in HL2GMED Lua scripting: events and hooks.

Events are specific happenings in the game world. One example of an event is when a player dies.
More examples are when a player spawns, takes damage, or disconnects.
There are even some events for non-game world things, such as drawing graphics on the Heads Up Display (or HUD, for short).
Sometimes, events even carry associated information. For example, if a player died, then the event might also carry information about which player died.

Whenever an event occurs, Game tells Lua that the event has happened.
Lua responds to an event by running hooks. Hooks are functions that are "hooked up" to an event.

In Practice

A "Hook" is a way to make a function run whenever something happens in the game.
A list of game-related hooks can be found here.
Example:

 
local MyHookFunction = function(pPlayer)
    if pPlayer:IsAlive() then
        dbg.Msg("Player Spawned.\n")
    end
end
 
hook.add("PlayerSpawn", "My PlayerSpawn hook", MyHookFunction)
 
So, every player respawn, this script will print "Player Spawned." into the console.

The function hook.add takes three arguments.

The first argument is the "type" of hook. There are many different types of hooks. There is one for when a player spawns, when a player dies, when someone connects, when someone takes damage, when someone presses a key, etc. The full list is available at the Documentation page.
Second argument is the unique"name" of created hook.
This name should identify what your hook function (known as a callback) does.

And the last one, third argument, is your hook function.
You can either store your hook function in a variable, and then pass that to this argument (like above), or you can do it inline:

 
hook.Add("PlayerSpawn", "blah blah", function()
    code code code
end)
 
Many coders use this way because it looks nicer.

Thank you for reading this article, see ya later!

JOIN HL2GMED DISCORD SERVER!