Functions

Functions are ordinary values in Lua: they can be stored in variables, passed as arguments, returned from other functions, and stored in tables.

Defining one

local function greet(name)
    return "Hello, " .. name
end

print(greet("Luak"))

local function foo() end is shorthand for declaring a local first, then assigning to it, which matters for a function that recurses by name.

Multiple return values

A function can return more than one value, and callers pick up as many as they use.

local function minmax(a, b)
    if a < b then
        return a, b
    end
    return b, a
end

local lo, hi = minmax(9, 3)
print(lo, hi) -- 3  9

Variable arguments

... in a parameter list captures any number of extra arguments.

local function sum(...)
    local total = 0
    for _, n in ipairs({...}) do
        total = total + n
    end
    return total
end

print(sum(1, 2, 3, 4)) -- 10

Default arguments

Lua has no default-argument syntax. Missing arguments come in as nil, so the idiom is the same or trick from Control Flow.

local function greet(name)
    name = name or "world"
    print("Hello, " .. name)
end

Closures

A function defined inside another captures the enclosing locals by reference. Each call to the outer function creates a fresh, independent set of captured variables.

local function make_counter()
    local count = 0
    return function()
        count = count + 1
        return count
    end
end

local next_id = make_counter()
print(next_id()) -- 1
print(next_id()) -- 2

Methods

function t:method(...) is shorthand for function t.method(self, ...), and t:method(...) calling syntax passes t as the first argument automatically.

local account = { balance = 0 }

function account:deposit(amount)
    self.balance = self.balance + amount
end

account:deposit(50)
print(account.balance) -- 50

account above is already a table, Lua's one data structure for everything from arrays to objects.