Is it possible to create a generator in GDScript 2.0 like in Python?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By abelgutierrez99


I have a function that calculates the positions of all the tiles and stores them into a list, that is returned. However, I would like to use the tiles positions as long as they are generated, without the need of a big array.

Take this simple Python code:

def my_generator(n):

    # initialize counter
    value = 0

    # loop until counter is less than n
    while value < n:

        # produce the current value of the counter
        yield value

        # increment the counter
        value += 1

# iterate over the generator object produced by my_generator
for value in my_generator(3):

    # print each value produced by generator

Extrated from here.

As you can see, I can access to the values as they are calculated. I was wondering if there is something similar in GDScript 2.0. I found the await keyword, but I can’t access the variable of interest in the process, only the final value.

:bust_in_silhouette: Reply From: spaceyjase

Not quite as fancy (essential missing the syntax sugar for yield), gdscript does support custom iterators: