← Back to Lua Course | Chapter 5: Functions | Lesson 6 of 7

Recursion and tail calls

A recursive function calls itself, and a tail call lets it do so without growing the stack.

In this page:

  1. Recursion and tail calls

Recursion and tail calls

A recursive function must be declared with local function so that its name is visible inside its own body. Each call uses stack space, so very deep recursion overflows. A call of the form return f(x) is a proper tail call in Lua and does not consume extra stack, so loops can be written as tail recursion.

Note: With local f = function ... end the name f is not yet visible inside the body, so use local function or declare first.

Example: Recursion and tail calls

lua
local function fact(n)
  if n <= 1 then return 1 end
  return n * fact(n - 1)
end
print(fact(5), fact(20))

local function sumTo(n, acc)
  acc = acc or 0
  if n == 0 then return acc end
  return sumTo(n - 1, acc + n)
end
print(sumTo(100000))

-- Output:
-- 120	2432902008176640000
-- 5000050000
Common Mistakes
  1. Writing local f = function and calling f inside it
  2. Forgetting the base case
  3. Adding work after the recursive call and losing the tail call
Chapter Summary
  • Use local function for recursion
  • A base case stops recursion
  • return f(x) is a tail call
  • Tail calls do not grow the stack

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.