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.
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.
iterating through a list and swapping elements. unfortunate, but ill use the above solutiong
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.