In Lua, functions are first-class values. A function has no inherent name: defining a function simply assigns an anonymous function object to a variable or table slot.
Multiple Return Values (Native Tuples)
Unlike languages that force developers to return arrays or tuples wrapped in objects, Lua natively supports returning multiple values on the VM stack:
-- Calculate both quotient and remainder in a single call
local function divmod(dividend, divisor)
local quotient = math.floor(dividend / divisor)
local remainder = dividend % divisor
return quotient, remainder
end
local q, r = divmod(17, 5)
print("Quotient: " .. q .. ", Remainder: " .. r) -- 3, 2
Multiple Assignment Behavior
local function getCoordinates()
return 100, 200, 300
end
-- 1. Capturing all values
local x, y, z = getCoordinates()
-- 2. Value truncation: extra returned values are discarded silently
local x_only = getCoordinates()
-- 3. In expressions, multiple returns are truncated to ONE value unless it is the LAST item!
print(getCoordinates(), "end") -- Prints: 100 end
print("start", getCoordinates()) -- Prints: start 100 200 300
Variadic Functions and the Vararg Expression (...)
Functions accepting an arbitrary number of parameters use the triple-dot ... syntax:
local function printLog(level, ...)
local args = {...} -- Packs arguments into an array table
local message = table.concat(args, " ")
print(string.format("[%s] %s", string.upper(level), message))
end
printLog("info", "Server started on port", 8080, "status: ready")
For high performance without table allocation overhead, use select:
local function sumNumbers(...)
local count = select("#", ...) -- Get number of varargs without table creation
local total = 0
for i = 1, count do
total = total + select(i, ...)
end
return total
end
Proper Tail Calls (Tail-Call Optimization)
Lua implements Proper Tail Calls. When the final action of a function is calling another function (with zero additional operations on the result), Lua does not push a new stack frame: it reuses the current stack frame.
-- NOT a tail call: addition occurs after g() returns
function f(x) return g(x) + 1 end
-- NOT a tail call: parentheses force evaluation of a single return value
function f(x) return (g(x)) end
-- VALID TAIL CALL: Constant stack space! Infinite recursion is safe!
function state_machine(state)
if state == "IDLE" then
return state_machine(check_input())
end
end
Exercises
- Write a function
table.unpackclone that unpacks an array table into multiple return values. - Implement an infinite state machine using tail-call recursion and prove that memory usage does not grow over 1,000,000 state transitions.
- Use
selectto write a variadic function finding the maximum value without allocating a temporary table.