+1 vote

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?

in Engine by (40 points)

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.

1 Answer

–1 vote
Best answer

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
by (4,044 points)
selected by

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

have a look here
https://docs.godotengine.org/en/stable/getting_started/scripting/gdscript/gdscript_basics.html?highlight=while#for

var fruits = ["banana", "apple", "pear"]
for fruit_index in fruit.size():
    print_debug(str(fruit_index +1 )+" "+fruit[fruit_index])
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.