Closures in GDScript
In GDScript, closures are implemented using anonymous functions. The int_seq
function returns an anonymous function that captures the i
variable, forming a closure.
To use this code in Godot:
- Create a new script and attach it to a node in your scene.
- Copy the above code into the script.
- Run the scene.
The output will be:
This demonstrates that the closure maintains its own state (i
) between calls, and that each new closure created by int_seq()
has its own independent state.
In GDScript, we use func():
to define anonymous functions, and .call()
to invoke them. The _ready()
function is Godot’s equivalent of a main()
function, automatically called when the script is loaded.
Note that in GDScript, we use print()
instead of fmt.Println()
for console output, and snake_case is preferred for function and variable names instead of camelCase.
The last feature of functions we’ll look at for now is recursion, which is also supported in GDScript.