Recursion in GDScript

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

extends Node

# This `fact` function calls itself until it reaches the
# base case of `fact(0)`.
func fact(n: int) -> int:
    if n == 0:
        return 1
    return n * fact(n - 1)

func _ready():
    print(fact(7))

    # In GDScript, we can define local functions within other functions.
    # This is similar to closures in some languages.
    var fib = func(n: int) -> int:
        if n < 2:
            return n
        # We can call the function recursively using its name
        return fib.call(n - 1) + fib.call(n - 2)

    print(fib.call(7))

To run this script, you would typically attach it to a Node in your Godot scene. The _ready() function is automatically called when the node enters the scene tree.

When executed, this script will output:

5040
13

In this example, we define two recursive functions:

  1. fact(n): A classic factorial function that recursively calculates n!.
  2. fib(n): A Fibonacci sequence generator defined as a local function within _ready().

GDScript supports recursive functions, allowing a function to call itself. The fact function demonstrates this by calling itself with n-1 until it reaches the base case of n == 0.

For the Fibonacci sequence, we define a local function using GDScript’s lambda syntax. This function can also call itself recursively. To invoke a lambda function in GDScript, we use the call() method.

It’s worth noting that while recursion can lead to elegant solutions for some problems, it can also lead to stack overflow errors for large inputs due to excessive function calls. In production code, especially for functions like Fibonacci, iterative solutions are often preferred for better performance and to avoid stack overflow issues.