Lua Functions

Functions are first-class values in Lua — you can assign them to variables, pass them as arguments, and return them from other functions.

Defining Functions

LUA
-- Basic function
local function greet(name)
    return "Hello, " .. name .. "!"
end

print(greet("Sita"))  -- "Hello, Sita!"

-- Function expression (anonymous function)
local double = function(x)
    return x * 2
end

print(double(5))  -- 10

Multiple Return Values

LUA
local function minmax(t)
    return math.min(table.unpack(t)), math.max(table.unpack(t))
end

local min, max = minmax({3, 1, 4, 1, 5, 9})
print(min, max)  -- 1  9

Variable Arguments (varargs)

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

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

Closures

A closure is a function that captures variables from its enclosing scope:

LUA
function make_counter(start)
    local count = start
    return function()
        count = count + 1
        return count
    end
end

local counter = make_counter(0)
print(counter())  -- 1
print(counter())  -- 2
print(counter())  -- 3

-- Each closure has its own independent state
local counter2 = make_counter(100)
print(counter2())  -- 101 (not affected by counter)

Higher-Order Functions

LUA
local function apply(func, value)
    return func(value)
end

local function square(x) return x * x end
local function cube(x) return x * x * x end

print(apply(square, 5))  -- 25
print(apply(cube, 5))    -- 125

-- map, filter, reduce
local function map(tbl, func)
    local result = {}
    for i, v in ipairs(tbl) do
        result[i] = func(v)
    end
    return result
end

local doubled = map({1, 2, 3}, function(x) return x * 2 end)
-- {2, 4, 6}

Tips

  • Use local for function declarations to keep them scoped.
  • Closures are powerful for callbacks, iterators, and factory patterns.
  • Lua functions can return multiple values — no need for wrapper objects.
  • Use ... for variadic functions.

Next: metatables.