How to skip an iteration in a for loop?

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

I want to skip an iteration of a for loop (but only sometimes so just increasing ‘i’ by 2 every time won’t work).
I have something like this:

for i in range(5):
    print(i)
    if i == 2:
        i += 1

and I would want it to print:

0
1
2
4

but this doesn’t work this way and it will just print: 0, 1, 2, 3, 4.
I guess this is because you are iterating through an array and of course it makes sense why it doesn’t work then.
But in other languages like Java or JavaScript this would work perfectly fine so I don’t know if I am doing something completly wrong here.

Here is an example of what I would write in JavaScript and what it would print:

for(let i = 0; i < 5; i++)
{
    console.log(i);
    if(i === 2)
    {
        i++;
    }
}

Console:

0
1
2
4
:bust_in_silhouette: Reply From: exuin

You can’t modify a for-loop variable like that with GDScript. One solution would be to use the continue keyword which skips to the next iteration of the for-loop (if i == 2: continue). Or just put the print statement inside the if-statement.

using continue is what i heard the most but sadly it doesn’t work for my problem. I just solved my problem by using a while loop instead of a for loop so i can change ‘i’ manually.

Thanks for your answer

vequa | 2021-01-10 20:52

:bust_in_silhouette: Reply From: vequa

Apparantly you can’t do something like this in GDScript. If you still need to do something like this you can use a while loop and increment ‘i’ manually.