for
The for command repeats a piece of script text a fixed number of times, with a parameter that counts.
Syntax
for <name> <start> <end> <step>
...
endfor
name is the counting parameter. start, end and step are numbers, integers or reals. step is never zero. for and endfor each stand alone on a line.
What it does
The preprocessor repeats the body once for each value name takes, so the parser sees the body as many times as it runs. The loop sets name to start, then adds step each pass. Inside the body %name is the current value. The body can be whole commands or part of one command’s arguments.
When James applies it
By the preprocessor, when it is read. The body is repeated before the parser sees it. A for is resolved before the phase of the parser matters, so it is legal anywhere.
Rules James adds
- The trip count is fixed once, when the loop opens, as in a Fortran
DOloop:MAX(FLOOR((end - start) / step) + 1, 0), in double precision. It is the same whether the three numbers are written as integers or reals. - A negative step counts down:
for i 10 1 -1runs 10 passes. Equal bounds give one pass. A step that does not divide the range leaves the last value short ofend:for x 0 1 0.3runs 4 passes, at 0, 0.3, 0.6 and 0.9. - A step of zero is an error.
- A loop that would run more than 1,000,000 passes is an error and runs none.
for,whenandwhilenest to 64 levels in all. Aforcan sit inside the arguments of another command.- A
fornever sits inside anifor holds one, and must close in the file that opened it.
Diagnostics
- E0307: the loop and another construct cross.
- E0309: the keyword shares its line with other input.
- E0310: more than 64
when,forandwhileconstructs are open. - E0311: the step is zero.
- E0312: the loop would run more than 1,000,000 passes.
- E0319: no
endforcloses it. - E0205: the counting name is an automatic parameter, as in
for pi 1 2 1. - E0216: the counting name holds a reserved character, as in
for a+b 1 2 1. - E0301: raised on a stray
endfor, the loop’s closer. - E0316: the closer does not match the open construct.
Example
The script tests/corpus/022-for-noninteger-step/input.tg, which make test runs:
for x 0 1 0.3
para y [%x*10];
endfor
The step is 0.3 and the end is 1, so the trip count is 4. The prep dump shows para y four times, with 0, 3, 6 and 9, which are %x*10 at x of 0, 0.3, 0.6 and 0.9.
See also
- endfor: the closer.
- break: leaves a loop early.
- while: the loop that tests a condition.
- Writing a script: the two control families.