Scripting 5.4. Loops

"For" loops

for variable from expression1 to expression2
for variable to expression
the statements between the for line and the matching endfor will be executed while a variable takes on values between two expressions, with an increment (raise) of 1 on each turn of the loop. If there is no from, the loop variable starts at 1.

The following script plays nine sine waves, with frequencies of 200, 300, ..., 1000 Hz:

    for i from 2 to 10
       Create Sound as pure tone: "tone", 1, 0, 0.3, 44100, i * 100, 0.2, 0.01, 0.01
       Play
       Remove
    endfor

The stop value of the for loop is evaluated on each turn. If the second expression is already less than the first expression to begin with, the statements between for and endfor are not executed even once.

“Repeat” loops

until expression
the statements between the matching preceding repeat and the until line will be executed again if the expression evaluates to zero or false.

The following script measures the number of trials it takes me to throw 12 with two dice:

    throws = 0
    repeat
       eyes = randomInteger (1, 6) + randomInteger (1, 6)
       throws = throws + 1
    until eyes = 12
    writeInfoLine: "It took me ", throws, " trials to throw 12 with two dice."

The statements in the repeat/until loop are executed at least once.

"While" loops

while expression
if the expression evaluates to zero or false, the execution of the script jumps after the matching endwhile.
endwhile
execution jumps back to the matching preceding while line, which is then evaluated again.

The following script forces the number x into the range [0; 2π):

    while x < 0
       x = x + 2 * pi
    endwhile
    while x >= 2 * pi
       x = x - 2 * pi
    endwhile

If the expression evaluates to zero or false to begin with, the statements between while and endwhile are not executed even once.

Links to this page


© ppgb 20140111