Closures in GDScript
# This function `int_seq` returns another function, which
# we define anonymously in the body of `int_seq`. The
# returned function closes over the variable `i` to
# form a closure.
func int_seq():
var i = 0
return func():
i += 1
return i
func _ready():
# We call `int_seq`, assigning the result (a function)
# to `next_int`. This function value captures its
# own `i` value, which will be updated each time
# we call `next_int`.
var next_int = int_seq()
# See the effect of the closure by calling `next_int`
# a few times.
print(next_int.call())
print(next_int.call())
print(next_int.call())
# To confirm that the state is unique to that
# particular function, create and test a new one.
var new_ints = int_seq()
print(new_ints.call())
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:
1
2
3
1
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.