Enumerate in GDScript

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

Hi, is there a way to implement the enumerate function in Python to GDScript?
Like this Python:

for i,n in enumerate([1,2,3]):
    print(i,n)

what’s the simple equivalent of this in GDScript?

It seems like the correct answer to this question is you can’t. You could possibly create an enumerate method, but you can’t do the implicit unpacking of an Array in the for loop, so it won’t really add anything.

BandanaLabcoat | 2021-04-23 15:51

:bust_in_silhouette: Reply From: klaas

Hi,
have a look …

if you mean const defined enums

enum fruits {banana, apple, pear}

# Called when the node enters the scene tree for the first time.
func _ready():
for fruit in fruits:
	print_debug(fruit) #prints banana, apple, pear

for fruit in fruits.size():
	print_debug(fruit)# prints 0,1,2

… or do you mean arrays?

for fruit in ["banana", "apple", "pear"]:
	print_debug(fruit) #prints banana, apple, pear

Kind of like this in Python:

for n, fruit in enumerate(['banana', 'apple', 'pear']):
    print(n+1, fruit) # prints 1 banana, 2 apple, 3 pear

Vincent William Rodr | 2020-08-27 09:29

have a look here
GDScript reference — Godot Engine (stable) documentation in English

var fruits = ["banana", "apple", "pear"]
for fruit_index in fruit.size():
    print_debug(str(fruit_index +1 )+" "+fruit[fruit_index])

klaas | 2020-08-27 09:37

1 Like