Previous: DO REPEAT, Up: Conditionals and Looping



11.4 LOOP

     LOOP [index_var=start TO end [BY incr]] [IF condition].
             ...
     END LOOP [IF condition].

LOOP iterates a group of commands. A number of termination options are offered.

Specify index_var to make that variable count from one value to another by a particular increment. index_var must be a pre-existing numeric variable. start, end, and incr are numeric expressions (see Expressions.)

During the first iteration, index_var is set to the value of start. During each successive iteration, index_var is increased by the value of incr. If end > start, then the loop terminates when index_var > end; otherwise it terminates when index_var < end. If incr is not specified then it defaults to +1 or -1 as appropriate.

If end > start and incr < 0, or if end < start and incr > 0, then the loop is never executed. index_var is nevertheless set to the value of start.

Modifying index_var within the loop is allowed, but it has no effect on the value of index_var in the next iteration.

Specify a boolean expression for the condition on LOOP to cause the loop to be executed only if the condition is true. If the condition is false or missing before the loop contents are executed the first time, the loop contents are not executed at all.

If index and condition clauses are both present on LOOP, the index clause is always evaluated first.

Specify a boolean expression for the condition on END LOOP to cause the loop to terminate if the condition is not true after the enclosed code block is executed. The condition is evaluated at the end of the loop, not at the beginning.

If the index clause and both condition clauses are not present, then the loop is executed MXLOOPS (see SET) times.

BREAK also terminates LOOP execution (see BREAK).

Loop index variables are by default reset to system-missing from one case to another, not left, unless a scratch variable is used as index. When loops are nested, this is usually undesired behavior, which can be corrected with LEAVE (see LEAVE) or by using a scratch variable as the loop index.

When LOOP or END LOOP is specified following TEMPORARY (see TEMPORARY), the LAG function may not be used (see LAG).