Recursion in Lua

Our example demonstrates recursion in Lua. Here’s the full source code:

-- This fact function calls itself until it reaches the
-- base case of fact(0).
function fact(n)
    if n == 0 then
        return 1
    end
    return n * fact(n - 1)
end

-- Main function to demonstrate recursion
function main()
    print(fact(7))

    -- Lua doesn't have closures in the same way as some other languages,
    -- but we can achieve similar functionality using local functions
    local function fib(n)
        if n < 2 then
            return n
        end
        return fib(n - 1) + fib(n - 2)
    end

    print(fib(7))
end

main()

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:

$ lua recursion.lua
5040
13

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.