Skip to reading
PCA Script Programming

11. Repeat, while and for each

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
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]
end

repeat 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.

Code example
function run()
    let result = []
    for each n in range(5, 0, -2)
        result = result + [n]
    end
    return result
end

Ordinary 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.

Page 18 of 357Permalink
Go to page