+4 votes

Hi dear community.

I'm trying to iterate a foreach loop using a for in like in the next example. I need to get the index to multiply the button size and spawn it in the correct spot.

func create_buttons():
    delete_buttons()
    for i, unit in selected_units: //i gives me an error
        if not buttons.has(unit.name):
            var but =  button.instance()
            but.connect_me(self, unit.name)
            var offset = 64
            but.rect_position = Vector2(buttons.size() * i + offset , $UI/NinePatchRect.rect_size / 2)
            $UI/NinePatchRect.add_child(but)
            buttons.append(but.name)

I know i can create an var outside the loop and the incrementate but thats ugly.

I'm new in gdscript and python. Any kind of help will be appreciated.

in Engine by (98 points)

2 Answers

+4 votes
Best answer

Presumably selected_units is an array.

In Python, you could use enumerate to get the functionality you're looking for.

for i, unit in enumerate(selected_units):

Iterating arrays in GDScript is not as full-featured as Python. If you want to have the index and item, you need to iterate through indices:

for i in range(selected_units.size()):
    if not buttons.has(selected_units[i].name):
    # etc
by (20,899 points)
selected by

For loop can be written shortly iterating all elements:

for i in selected_units.size():

True, but I tend to default to the range() construction as more explicit (and out of Python habits).

+3 votes

You can do it like this too:

for i in len(selected_units):
    var unit = selected_units[i]
    #...

I tend to not use range in for loops because although it looks nicer in the Python sense, Godot does not have iterables, which means range returns an array, so if your list is huge it will create an array of that size everytime (impact is negligible for small lists).

Edit: actually this was true in Godot 2 but an exception for for loops might have changed in Godot 3, I'm not exactly sure right now

by (28,744 points)
edited by
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.