Recursion in AngelScript

Our example demonstrates recursive functions in AngelScript. Here’s a classic implementation of factorial calculation using recursion.

void main()
{
    print(fact(7));

    // Closures can also be recursive in AngelScript
    funcdef int fibonacci(int);
    fibonacci@ fib = function(int n)
    {
        if (n < 2)
            return n;
        return fib(n - 1) + fib(n - 2);
    };

    print(fib(7));
}

int fact(int n)
{
    if (n == 0)
        return 1;
    return n * fact(n - 1);
}

This fact function calls itself until it reaches the base case of fact(0).

In the main function, we first call and print the result of fact(7).

AngelScript also supports recursive closures. We define a function type fibonacci and then create a closure that calculates Fibonacci numbers recursively.

Note that in AngelScript, we use the funcdef keyword to define a function type, and the @ symbol to declare a function handle.

The output of this program would be:

5040
13

This example showcases how recursion can be used both in regular functions and in closures in AngelScript. The factorial function demonstrates simple recursion, while the Fibonacci closure shows a more complex recursive pattern.