Functions in Lua
Functions are blocks of code that can be called and reused throughout your program. Lua provides a flexible and powerful function system.
Basic Function Syntax
Functions in Lua can be defined in several ways:
basic_functions.lua
-- Basic function definition
function sayHello()
print("Hello, world!")
end
-- Call the function
sayHello() -- Output: Hello, world!
-- Functions with parameters
function greet(name)
print("Hello, " .. name .. "!")
end
greet("Alice") -- Output: Hello, Alice!
-- Function with return value
function add(a, b)
return a + b
end
local sum = add(5, 3)
print("Sum: " .. sum) -- Output: Sum: 8
Functions as Variables
In Lua, functions are first-class values, meaning they can be stored in variables and passed as arguments:
function_variables.lua
-- Function assigned to a variable
local multiply = function(a, b)
return a * b
end
print("Product: " .. multiply(4, 5)) -- Output: Product: 20
-- Alternative function syntax
local divide = function(a, b)
if b == 0 then
return "Error: Division by zero"
end
return a / b
end
print(divide(10, 2)) -- Output: 5
print(divide(10, 0)) -- Output: Error: Division by zero
-- Functions as arguments
function applyOperation(func, x, y)
return func(x, y)
end
local result = applyOperation(multiply, 3, 4)
print("Applied operation: " .. result) -- Output: Applied operation: 12
Closures and Scope
Lua functions can access variables from their outer scope, forming what's known as a closure:
closures.lua
-- Function that returns a function (closure)
function createCounter(initialValue)
local count = initialValue or 0
-- Return a function that can access the local 'count' variable
return function()
count = count + 1
return count
end
end
-- Create two different counters
local counter1 = createCounter(0)
local counter2 = createCounter(10)
-- Each counter maintains its own state
print("Counter 1:", counter1()) -- Output: Counter 1: 1
print("Counter 1:", counter1()) -- Output: Counter 1: 2
print("Counter 2:", counter2()) -- Output: Counter 2: 11
print("Counter 1:", counter1()) -- Output: Counter 1: 3