for repeats a block once for every item in something. The simplest form repeats a number of times:
Wave 0
Wave 1
Wave 2
for i in 3 is short for for i in range(3): i takes the values 0, 1 and 2. The end value is never included.
range(): Start, End and Step
range() takes up to three numbers: where to start, where to stop (not included) and how far to step:
[0, 1, 2, 3, 4]
[2, 3, 4, 5]
[0, 5, 10, 15]
[10, 7, 4, 1]
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
A negative step counts down. range() takes integers: a float argument is cut to a whole number, so range(0, 2, 0.5) fails with a zero step. For steps like 0.5, loop over integers and divide.
Looping Over an Array
Put the array after in and the loop variable holds one item each time:
Spawning a slime
Spawning a bat
Spawning a skeleton
You can type the loop variable: for enemy: String in enemies:.
Getting the Index
GDScript has no enumerate(). Loop over the indexes instead:
1. Ana
2. Bo
3. Chidi
Looping Over a Dictionary
A for loop over a dictionary gives its keys. Read the value with the key:
potion: 3
arrow: 20
key: 1
3
20
1
Keys come out in the order they were added.
Looping Over a String and a Grid
A string gives its characters, one at a time. A grid of tiles is two loops, one inside the other:
G
O
!
(0, 0)
(1, 0)
(2, 0)
(0, 1)
(1, 1)
(2, 1)
Nested loops like this one walk every cell of a tile grid, row by row.
break and continue
break leaves the loop. continue skips to the next item:
Rolled 3
Rolled 5
Six! Stop rolling.
Removing Items While Looping
Removing from the array you are looping over shifts the items and the loop skips some. Loop backwards by index, or let filter() build a new array:
[10, 5, 8]
[9, 7]
Loops in a Running Game
A for loop finishes inside one frame, so a loop of 100,000 steps freezes the game until it is done. For something that happens over time, such as a countdown, use _process(delta), a Timer or await instead of a loop.
Frequently Asked Questions
How do I write a for loop in Godot?
Write for i in 5: and indent the body under it. The loop runs 5 times with i from 0 to 4. To loop over a list, put the list after in: for enemy in enemies:.
How do I get the index in a GDScript for loop?
Loop over the indexes and read the item: for i in items.size(): and then items[i]. GDScript has no enumerate().
How do I loop backwards in GDScript?
Use range() with a negative step: for i in range(10, 0, -1): counts 10 down to 1. The end value is never included. To walk an array backwards, use range(items.size() - 1, -1, -1).
Can I remove items from an array while looping over it?
Not safely: removing shifts the items and the loop skips some. Loop backwards by index and call remove_at(i), or build a new array with filter().