Recursion in UnrealScript

Our example demonstrates recursive functions in UnrealScript. Here’s a classic implementation:

class RecursionExample extends Object;

// This `Factorial` function calls itself until it reaches the
// base case of `Factorial(0)`.
static function int Factorial(int n)
{
    if (n == 0)
    {
        return 1;
    }
    return n * Factorial(n-1);
}

static function int Fibonacci(int n)
{
    if (n < 2)
    {
        return n;
    }
    return Fibonacci(n-1) + Fibonacci(n-2);
}

static function Execute()
{
    local int factResult, fibResult;

    factResult = Factorial(7);
    `log("Factorial(7) =" @ factResult);

    fibResult = Fibonacci(7);
    `log("Fibonacci(7) =" @ fibResult);
}

defaultproperties
{
}

In this example, we define two recursive functions: Factorial and Fibonacci.

The Factorial function calculates the factorial of a given number. It calls itself with a decremented value until it reaches the base case of 0.

The Fibonacci function calculates the nth Fibonacci number. It recursively calls itself for n-1 and n-2 until it reaches the base cases of 0 or 1.

In the Execute function, we demonstrate the usage of these recursive functions by calculating the factorial and Fibonacci number for 7.

To run this code in Unreal Engine:

  1. Create a new UnrealScript file named RecursionExample.uc in your project’s Classes folder.
  2. Copy the above code into the file.
  3. Compile the script.
  4. In your game code or through the console, call RecursionExample.Execute().

The output will be logged to the Unreal Engine log, which should show:

Factorial(7) = 5040
Fibonacci(7) = 13

Note that UnrealScript doesn’t support closures or anonymous functions like some modern languages, so we’ve implemented the Fibonacci function as a regular static function instead of a closure.

This example demonstrates how recursive functions can be implemented and used in UnrealScript for solving problems that have a naturally recursive structure, such as factorial calculations and Fibonacci sequences.