Lua Recursion
A recursive function calls itself. Each call works on a smaller piece of the problem until it reaches a base case that can be answered directly. Recursion is natural for tree-shaped data: nested tables, file systems, menus, game scene graphs.
local function factorial(n)
if n <= 1 then
return 1 -- base case
end
return n * factorial(n - 1) -- recursive case
end
for n = 0, 6 do
io.write(n, "! = ", factorial(n), "\n")
end0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
Note: Use
local function name()for recursive locals. Withlocal name = function() … end, the name isn't in scope yet inside the body, so the recursive call would look up a globalnameand fail.
Walking nested tables
Tables can contain tables to any depth. A recursive function handles any depth without knowing it in advance:
local menu = {
"File",
{ "New", "Open", { "Recent 1", "Recent 2" } },
"Edit",
{ "Copy", "Paste" },
}
local function countItems(node)
local total = 0
for _, item in ipairs(node) do
if type(item) == "table" then
total = total + countItems(item)
else
total = total + 1
end
end
return total
end
local function show(node, depth)
depth = depth or 0
for _, item in ipairs(node) do
if type(item) == "table" then
show(item, depth + 1)
else
print(string.rep(" ", depth) .. item)
end
end
end
print("items:", countItems(menu))
show(menu)items: 8
File
New
Open
Recent 1
Recent 2
Edit
Copy
Paste
Divide and conquer
Binary search halves the range on every call, so it needs only about 20 calls for a million items:
local function binarySearch(list, target, lo, hi)
lo, hi = lo or 1, hi or #list
if lo > hi then return nil end
local mid = (lo + hi) // 2
if list[mid] == target then
return mid
elseif list[mid] < target then
return binarySearch(list, target, mid + 1, hi)
else
return binarySearch(list, target, lo, mid - 1)
end
end
local sorted = { 3, 8, 15, 23, 42, 57, 91 }
print(binarySearch(sorted, 42))
print(binarySearch(sorted, 4))5
nil
Proper tail calls
When a function's last action is return f(args), Lua performs a proper tail call: it reuses the current stack frame instead of adding a new one. Tail-recursive functions can therefore recurse millions of times without a stack overflow:
local function sumTo(n, acc)
acc = acc or 0
if n == 0 then return acc end
return sumTo(n - 1, acc + n) -- a tail call
end
print(sumTo(1000000))
local function notTail(n)
if n == 0 then return 0 end
return n + notTail(n - 1) -- NOT a tail call: the + happens after
end
local ok, err = pcall(notTail, 1000000)
print(ok, err:match("stack overflow") ~= nil)500000500000
false true
Only return f(x) is a tail call. return f(x) + 1, return (f(x)) and f(x); return are not.
Recursion vs loops
Naive recursion can repeat work. The textbook Fibonacci recursion calls itself exponentially many times; a loop (or memoisation) is far faster:
local calls = 0
local function fibSlow(n)
calls = calls + 1
if n < 2 then return n end
return fibSlow(n - 1) + fibSlow(n - 2)
end
local function fibLoop(n)
local a, b = 0, 1
for _ = 1, n do a, b = b, a + b end
return a
end
print(fibSlow(20), calls)
print(fibLoop(20), fibLoop(80))6765 21891
6765 23416728348467685
Test yourself
What stops a recursive function from calling itself forever?
- The garbage collector
- A base case
- A
goto - A metatable
Which return statement is a proper tail call?
return f(n) + 1return (f(n))return f(n - 1)return 1, f(n)
Why write local function walk() instead of local walk = function() for a recursive function?
- It is faster to type
- The name is in scope inside the body, so the recursive call finds the local
- It makes the function global
- There is no difference