Garry's Mod Wiki

Concepts - Functions

What is a Function

A Function is a reusable block of code defined using the function and end keywords. Functions allow you to group statements together, promoting code organization and reusability

Example

local function pow() print("The result of 2 * 2 is " .. 2 * 2) end pow()

Output

The result of 2 * 2 is 4

Parameter

Functions with parameters in Lua allow you to pass values into the function when it's called, enabling the function to perform specific actions based on those input values. Parameters act as placeholders for the actual values used in the function. By using parameters, functions can be more versatile and reusable, accepting different inputs and producing different outputs based on the provided arguments.

Example

local function pow(num) print("The result of " .. num .. " * " .. num " is " .. num * num) end pow(2)

Output

The result of 2 * 2 is 4

Return

The return statement is used in a function to specify the value(s) that the function should produce or output. When a function encounters the return statement, it immediately stops executing and returns the specified value(s) back to the caller. This allows functions to provide results to the code that called them, enabling the use of the function's output in other parts of the program.

Example

local function pow(num) return num * num end local number = pow(2) print("The result of 2 * 2 is " .. number)

Output

The result of 2 * 2 is 4

The return statement can be used without a value to simply exit the function, terminating its execution without returning any specific value. This can be useful when you want to stop the function at a certain point without providing an output back to the caller.

Example

local function SetHealth(ply, health) if not IsValid(ply) or not ply:IsAlive() then return end ply:SetHealth(health) print("Set the health of " .. ply:Nick() .. " to " .. health) end SetHealth(Entity(1), 100) Entity(1):Kill() SetHealth(Entity(1), 100)

Output

Set the health of User to 100 -- No Output because the Player is Dead

Assignment of a variable

In Lua, you can assign a function to a variable by using the function name without parentheses.

Example

local pow = function(num) return num * num end

Here, the pow variable now holds the function, and you can call this function by using pow(). This technique allows you to create and store anonymous functions in variables, making it easy to pass functions around in your Lua code. Now you can pass the variable in other functions like concommand.Add.

local pow = function(ply, cmd, args) local num = args[1] return num * num end concommand.Add("pow" , pow)