11. Repeat, while and for each
function run()
let total = 0
repeat 3 times
total += 2
end
let tries = 0
while tries < 3
tries += 1
end
for each value, index in [10, 20, 30]
total += value
end
return [total, tries]
endrepeat is for a fixed count. while keeps going while a test is true. for each visits every value in an array; the optional second name receives its zero-based index. When given a dictionary, for each visits its keys.
A numeric for-loop is written with range(): for each n in range(1, 6) produces 1, 2, 3, 4 and 5. The stop value is excluded. range_inclusive(1, 5) includes 5. A negative step counts down. A zero step is an error.
function run()
let result = []
for each n in range(5, 0, -2)
result = result + [n]
end
return result
endOrdinary loops have a 100,000-iteration guard. They do not automatically spread work over frames. A loop that waits for player action needs a wait in its body; otherwise it can freeze the current frame until the guard stops it.
