How to change the loop variable in a for loop?

Godot Version

v4.2.1.stable.official [b09f793f5]

Question

How do you change the loop variable within a loop?
For example, how would you write:

for(int i = 0;i<10;i++){
if(foo){
bar;
i--;
}
}

hmm…
this works:

var i = 0
while(i<10):
  if(foo):
    bar
    i -= 1
  i += 1

but is less readable, var i is now outside loop scope, continues and the iteration have to be handled.
If anyone figures out a better solution, please add it.

1 Like

What is your end goal?

This is the best solution in GDScript, there is no way to capture such a variable within the loop scope.

1 Like

iterating through a list and swapping elements. unfortunate, but ill use the above solutiong

1 Like

Oh in that case you can literally do something like

for item in list:
  item.do_thing()

This will call the do_thing() method on every item in your list.
You can of course also add conditions so only certain items within your list are affected.

for item in list:
   if item.name = "Apple":
      print("Item ", item, " was the apple!")

It’s not a good idea to edit a list while iterating through it like that, and swapping items in the list is easier with indecies instead of just references.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.