Lesson 24 of 55
8 mins readPython Proper Tail Call Optimization (TCO)
In Plain English
Lua guarantees **Proper Tail Call Optimization** (TCO). A call in tail position `return func(args)` reuses the current stack frame, allowing infinite recursive state transitions without stack overflows.
Deep Dive: How It Works
Tail Call Position: Must be in the exact form `return f(args)` with no operations after the call.
Not a Tail Call: `return 1 + f(args)` or `f(args); return` (these allocate stack frames).
State Machines: Transitions between game or parsing states with zero memory growth.
Core Rules to Remember

Proper Tail Calls: `return func(args)` executes without allocating additional stack frames.

Infinite State Transitions: Ideal for recursive algorithms and state-driven game engines.
Live Interactive Example
Hit Run Code to see it liveTail Recursive Countdown
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
Output Console
Click "Run Code" to view the rendered output.
How it works: return count_down(...) was in tail position, executing in O(1) stack space.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Write Tail-Recursive Accumulator
Define `local function sum_tail(n, acc) acc = acc or 0 if n <= 0 then return acc end return sum_tail(n - 1, acc + n) end`.
Print `"Tail Sum: " .. sum_tail(5)`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.