Recursion in UnrealScript
Our example demonstrates recursive functions in UnrealScript. Here’s a classic implementation:
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:
- Create a new UnrealScript file named
RecursionExample.uc
in your project’s Classes folder. - Copy the above code into the file.
- Compile the script.
- In your game code or through the console, call
RecursionExample.Execute()
.
The output will be logged to the Unreal Engine log, which should show:
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.