Lesson 4 of 8
Functions
Learn to write , return several values at once, and use . In Lua, functions are values you can store in tables and pass to other functions.
local function greet(name)
return "Hello, " .. name .. "!"
end
print(greet("Ada"))
-- Multiple return values — common in Lua:
local function divide(a, b)
if b == 0 then
return nil, "division by zero" -- value, error pattern
end
return a / b
end
local result, err = divide(10, 0)
if not result then
print("Error: " .. err)
end
-- Missing arguments are nil; extra ones are dropped:
local function hello(name)
name = name or "stranger" -- idiomatic default
print("Hi, " .. name)
end
hello() -- Hi, stranger-- Functions are values:
local shout = function (s) return s:upper() .. "!" end
local ops = {
add = function (a, b) return a + b end,
mul = function (a, b) return a * b end,
}
print(ops.add(2, 3)) -- 5
-- Closures — functions remember their surroundings:
local function makeCounter()
local count = 0
return function ()
count = count + 1
return count
end
end
local next = makeCounter()
print(next(), next(), next()) -- 1 2 3
-- Variadic functions:
local function sum(...)
local total = 0
for _, n in ipairs({ ... }) do
total = total + n
end
return total
end
print(sum(1, 2, 3, 4)) -- 10Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.