Nanfeng

Notes on software development, code, and curious ideas

Functions in Lua

Functions are first-class values in Lua. They can be stored in tables, passed as arguments, returned from other functions, and created anonymously.

1
2
3
4
local function distance(x1, y1, x2, y2)
local dx, dy = x2 - x1, y2 - y1
return math.sqrt(dx * dx + dy * dy)
end

The declaration above assigns a function value to a local name. Prefer local functions unless a global API is intentional.

Multiple results

1
2
3
4
5
local function divide(a, b)
return a // b, a % b
end

local quotient, remainder = divide(17, 5)

A function call produces all results only in certain positions, such as the final expression of an assignment, argument list, or return statement. Parentheses force a call to one result: (divide(17, 5)).

Variadic functions

1
2
3
4
5
6
7
local function sum(...)
local total = 0
for index = 1, select("#", ...) do
total = total + select(index, ...)
end
return total
end

select("#", ...) preserves the count even when arguments include nil. {...} does not by itself preserve trailing nil values.

Lua has positional parameters, but a table provides readable named options:

1
2
3
4
5
local function connect(options)
local host = assert(options.host)
local port = options.port or 443
return host, port
end

Recursion and tail calls

A call is in tail position when its results are returned directly:

1
2
3
4
5
local function find(node, wanted)
if not node then return nil end
if node.value == wanted then return node end
return find(node.next, wanted)
end

Proper tail calls reuse stack space. Adding arithmetic, another result, or work after the call removes tail position. Use recursion where it expresses the structure clearly, but prefer loops for simple linear traversal.

+