Recursion in Lua
Our example demonstrates recursion in Lua. Here’s the full source code:
This program demonstrates recursive functions in Lua.
The fact
function is a classic example of recursion, calculating the factorial of a given number. It calls itself with a smaller argument until it reaches the base case of fact(0)
.
In the main
function, we first call fact(7)
to calculate 7!.
Next, we define a local function fib
inside main
. This function calculates the nth Fibonacci number recursively. Unlike some other languages, Lua doesn’t require special syntax for recursive local functions.
Finally, we call fib(7)
to calculate the 7th Fibonacci number.
To run the program, save it as recursion.lua
and use the Lua interpreter:
The output shows the result of fact(7)
(which is 5040) and fib(7)
(which is 13).
Lua supports recursive functions naturally, making it easy to implement algorithms that are naturally expressed in a recursive manner.