For...=...To...Step...Do...Od

The For statement is used to repeat a loop based on a counter.

Syntax

For variable = number
  To number
Step number
Do
  ...	;
Od;

For variable = number is the counter and initial value.

To number is upper limit.

Step number is optionally step size.

... ; is repeated code.

Variable must be declared as a Number. The initial value, limit, and step values are calculated once before the loop is executed the first time. At the end of each loop variable is incremented with the Step value. It is possible (but not advisable) to modify the variable within the loop.

If the Step keyword is omitted, the step value defaults to 1.

The Do … Od loop is executed while:

  • Variable is smaller or equal to the To value if the Step value is greater or equal to 0.
  • Variable is larger or equal to the To value if the Step value is negative.

You can use the Break command to terminate the loop unconditionally.

Example

This example locates a slash in a path by walking through it using the substring function.

Parameter Text Path;
Var Number Count;
For Count = 1 To length(Path) Do
  If substring (Path, Count, 1) = "\" Then
    Break;
  Fi;
Od; 

Parameter Text Path; The parameter Path is the input passed to this script.

Var Number Count; The count variable needed in the statement For. Must be declared before this statement.

The code If substring (Path, Count, 1) = "\" Then Break; between Do and OD will be repeated until either the function substring (Path, Count, 1) is equal to "\" or Count is larger than length (Path). When substring (Path, Count, 1) is equal to "\", the loop is terminated. Count at that point will contain the position of "\" in Path. You can use Count in the remainder of the script, because Count is declared outside the For loop which means that its scope is not limited to the For loop. Although this is a valid example, the file name manipulation methods provided in KCM Core are more convenient.