Functions, Closures & Tail Calls
Functions in PyLua are first-class lexical closures. They can be passed as arguments, returned from other functions, stored in tables, and execute with automatic tail call optimization.
1. Defining Functions
PyLua supports both C-style curly braces and standard Lua syntax for function definitions:
-- Modern C-Style Braces:
function multiply(a, b) {
return a * b
}
-- Anonymous function / Lambda:
square = function(x) { return x * x }
-- Higher-order function:
function applyTwice(fn, val) {
return fn(fn(val))
}
print(applyTwice(square, 3)) -- (3^2)^2 = 81
2. Multiple Return Values
PyLua functions can return any number of results directly:
function getCoordinates() {
return 1920, 1080, 60 -- x, y, refreshRate
}
width, height, hz = getCoordinates()
print("Resolution: " .. width .. "x" .. height .. " @ " .. hz .. "Hz")
If a function call is the last argument in an expression list, all returned values are preserved. If used in the middle of a list, PyLua adjusts the returns to exactly 1 value.
3. Variadic Functions (Varargs `...`)
A function that accepts an indefinite number of parameters defines ... as its final parameter:
function sumAll(...) {
total = 0
args = { ... } -- Pack into a table
for i, v in ipairs(args) {
total = total + v
}
return total
}
print(sumAll(10, 20, 30, 40)) -- 100
Avoid creating temporary tables for large argument lists by using select("#", ...) to count arguments and select(i, ...) to index without memory allocation.
4. Method Call Syntactic Sugar (`:`)
The colon operator : provides clean object-oriented syntax by implicitly passing the caller as the first parameter (named self):
Entity = { x = 0, y = 0 }
-- Method declaration: implicitly injects parameter 'self'
function Entity:move(dx, dy) {
self.x = self.x + dx
self.y = self.y + dy
}
-- Method invocation: implicitly passes 'Entity' as 'self'
Entity:move(5, 10)
print(Entity.x, Entity.y) -- 5, 10
-- Equivalent to:
Entity.move(Entity, 5, 10)
5. Proper Tail Calls (TCO)
When a function's last statement is a direct return of another function call (e.g. return f(x)), the PyLua virtual machine performs a proper tail call:
Standard Call [OP_CALL]: [Caller Frame] ──▶ [Callee Frame 1] ──▶ [Callee Frame 2] ... ──▶ Stack Overflow! Proper Tail Call [OP_TAILCALL]: [Caller Frame] ──▶ Overwrites active frame with [Next Function Frame]! Stack depth remains constant: O(1) memory!
-- Infinite state machine loop without stack overflow:
function stateA(count) {
if (count > 1000000) { return "Done!" }
return stateB(count + 1) -- OP_TAILCALL: Reuses stack slot
}
function stateB(count) {
return stateA(count + 1) -- OP_TAILCALL: Reuses stack slot
}
print(stateA(0)) -- Completes in microseconds with 0 stack growth!