Skip to content
the poor coder

glua how to call a hook

Poor Man
Published
Reading time
1 min read
On this page

Calling a Hook in GLua#

As a GLua developer, calling a hook is an essential part of creating addons for Garry's Mod. If you're not familiar with what a hook is, it's a function that runs when a specific event happens in the game.

Method 1: Using the hook library#

The easiest way to call a hook is by using the hook library. This library provides several functions that allow you to hook into specific events in the game. The most commonly used function is hook.Add.

Here's an example of how to use hook.Add to call a hook:

Text

hook.Add("PlayerSpawn", "MyAddon_PlayerSpawn", function(ply)
    print(ply:Nick() .. " has spawned!")
end)

In this example, we're using hook.Add to hook into the PlayerSpawn event. When a player spawns, the function we provided will be called. This function will print the player's name to the console.

Method 2: Using the GM:hook function#

If you're developing an addon that extends the base functionality of Garry's Mod, you can also use the GM:hook function to call hooks.

Here's an example of how to use GM:hook:

Text

function GM:PlayerSpawn(ply)
    print(ply:Nick() .. " has spawned!")
end

In this example, we've defined a function called GM:PlayerSpawn. When a player spawns, this function will be called automatically by Garry's Mod. Inside the function, we're printing the player's name to the console.

Method 3: Using the RunString function#

If you're working with code that isn't part of an addon or gamemode, you can use the RunString function to call hooks.

Here's an example of how to use RunString:

Text

local code = [[
    hook.Add("PlayerSpawn", "MyAddon_PlayerSpawn", function(ply)
        print(ply:Nick() .. " has spawned!")
    end)
]]

RunString(code)

In this example, we're using the RunString function to execute some code that hooks into the PlayerSpawn event. When a player spawns, our function will be called and it will print the player's name to the console.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC