Functions in Lua
Functions are reusable blocks of code that perform specific tasks. They're fundamental to writing clean, organized, and maintainable code. Lua treats functions as first-class values, meaning they can be stored in variables, passed as arguments, and returned from other functions. This makes Lua incredibly powerful for functional programming. Let's explore everything about functions!
Defining Functions
There are several ways to define functions in Lua:
Basic Function Definition
function greet()
print("Hello, World!")
end
greet() -- Call the function
Function as Variable
local greet = function()
print("Hello, World!")
end
greet() -- Same result
local for function
variables
to avoid polluting the global namespace:
local function greet()
print("Hello!")
end
Click Run to execute your code
Function Parameters
Functions can accept input through parameters:
local function greet(name)
print("Hello, " .. name .. "!")
end
greet("Alice") -- Hello, Alice!
greet("Bob") -- Hello, Bob!
Multiple Parameters
local function add(a, b)
return a + b
end
local result = add(5, 3)
print(result) -- 8
Default Parameters
Lua doesn't have built-in default parameters, but you can use or:
local function greet(name)
name = name or "Guest" -- Default to "Guest" if nil
print("Hello, " .. name)
end
greet() -- Hello, Guest
greet("Alice") -- Hello, Alice
Click Run to execute your code
Return Values
Functions can return values using the return statement:
local function square(x)
return x * x
end
local result = square(5)
print(result) -- 25
Multiple Return Values
Lua functions can return multiple valuesβa unique and powerful feature!
local function divmod(a, b)
local quotient = math.floor(a / b)
local remainder = a % b
return quotient, remainder
end
local q, r = divmod(17, 5)
print("Quotient:", q) -- 3
print("Remainder:", r) -- 2
string.find() which
returns start and end positions.
Click Run to execute your code
Variadic Functions
Functions can accept variable numbers of arguments using ...:
local function sum(...)
local total = 0
for i, v in ipairs({...}) do
total = total + v
end
return total
end
print(sum(1, 2, 3)) -- 6
print(sum(10, 20, 30, 40)) -- 100
Accessing Variadic Arguments
local function printAll(...)
local args = {...} -- Pack into table
for i, v in ipairs(args) do
print(i, v)
end
end
printAll("apple", "banana", "cherry")
Mixed Parameters
local function greetAll(greeting, ...)
local names = {...}
for i, name in ipairs(names) do
print(greeting .. ", " .. name .. "!")
end
end
greetAll("Hello", "Alice", "Bob", "Charlie")
Click Run to execute your code
Functions as First-Class Values
In Lua, functions are values that can be stored and passed around:
Storing in Variables
local function add(a, b)
return a + b
end
local operation = add -- Store function in variable
print(operation(5, 3)) -- 8
Passing to Other Functions
local function apply(func, a, b)
return func(a, b)
end
local function multiply(x, y)
return x * y
end
local result = apply(multiply, 4, 5)
print(result) -- 20
Returning Functions
local function createMultiplier(factor)
return function(x)
return x * factor
end
end
local double = createMultiplier(2)
local triple = createMultiplier(3)
print(double(5)) -- 10
print(triple(5)) -- 15
Click Run to execute your code
Anonymous Functions
Functions without names, often used as callbacks:
-- Sort with custom comparator
local numbers = {5, 2, 8, 1, 9}
table.sort(numbers, function(a, b)
return a > b -- Sort descending
end)
-- Map function
local function map(array, func)
local result = {}
for i, v in ipairs(array) do
result[i] = func(v)
end
return result
end
local doubled = map({1, 2, 3}, function(x)
return x * 2
end)
-- doubled = {2, 4, 6}
Variable Scope
Variables in functions follow scoping rules:
local x = 10 -- Global to this file
local function test()
local y = 20 -- Local to function
print(x) -- Can access outer x
print(y) -- Can access local y
end
test()
-- print(y) -- Error: y is not accessible here
- Local variables are only accessible within their block
- Functions can access variables from outer scopes
- Parameters are local to the function
- Always use
localto avoid global pollution
Practice Exercise
Try these function challenges:
Click Run to execute your code
Summary
In this lesson, you learned:
- Defining functions with
functionkeyword - Function parameters and default values
- Returning single and multiple values
- Variadic functions with
... - Functions as first-class values
- Anonymous functions for callbacks
- Variable scope in functions
What's Next?
You've mastered the basics of functions! Next, we'll explore closures βone of Lua's most powerful features. You'll learn how functions can "remember" their environment, enabling advanced patterns like private variables, factories, and decorators. Let's continue! π
Enjoying these tutorials?