LU Lua

Lua: Functions & Closures

What you will learn

Lua treats functions as first-class values — you can store them in variables, pass them as arguments, and create anonymous functions (closures).

Defining a function

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

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

The .. operator concatenates strings. return sends a value back to the caller.

Anonymous functions

local double = function(x)
    return x * 2
end
print(double(5))  -- 10

Functions can be stored in variables and passed around.

Closures (upvalues)

Functions can capture local variables from their enclosing scope — this is called an upvalue:

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

local counter = makeCounter()
print(counter())  -- 1
print(counter())  -- 2
print(counter())  -- 3

The inner function "remembers" the count variable even after makeCounter() has returned.

Multiple return values

Lua functions can return multiple values (like Go):

function min_max(list)
    return math.min(table.unpack(list)), math.max(table.unpack(list))
end

local lo, hi = min_max({3, 1, 4, 1, 5})
print(lo, hi)  -- 1 5

Common mistakes

  • Forgetting end to close the function body.
  • Using return outside a function cause (only valid inside a function body).
  • Confusing .. (concatenation) with + (addition).
  • Returning multiple values but receiving them into a single variable — extra values are discarded.

Quick check below!