Skip to reading
GDScript Programming & Godot

10. For loops, while loops and range

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView PDF page
Code example
func run() -> Array:
    var total: int = 0
    for amount in [10, 20, 30]:
        total += amount
    var attempts: int = 0
    while attempts < 3:
        attempts += 1
    var odds: Array = []
    for number in range(5, 0, -2):
        odds.append(number)
    return [total, attempts, odds]

A for-loop visits a collection or a range. A dictionary loop visits its keys. range(stop) starts at 0 and excludes stop. range(start, stop, step) adds a start and a step; use a negative step to count down.

A while-loop repeats while its condition is true. Change the tested state inside it. Ordinary GDScript does not get PCA Script’s automatic loop guard. A loop that waits on player input must yield to the engine or it can block the frame indefinitely.

Code example
func run() -> Array:
    var kept: Array = []
    for number in range(10):
        if number == 2:
            continue
        if number == 5:
            break
        kept.append(number)
    return kept

There is no native do-while statement. A while true loop with a final test and break expresses the same pattern. PCA also supplies callable-based loop helpers, documented later.

Page 18 of 378Permalink
Go to page