10. For loops, while loops and range
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.
func run() -> Array:
var kept: Array = []
for number in range(10):
if number == 2:
continue
if number == 5:
break
kept.append(number)
return keptThere 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.
