Chapter 7. Loops and such

The last thing you need for minimal language completeness is some sort of looping construct. Ripley comes with two. The first is a 'loop' operand that continues executing an executable array until the 'exit' operator is called. The 'exit' operator sets a flag which is caught by the while when it is next executed and the while halts. Below is an example of the loop operator:

Example 7-1. Counter to 10

/count 0 def
{ /count count 1 add def 
 "count = " print
 count print
 "\n" print
 count 10 gt
 { exit } if
} loop

In this example we use the 'loop' operand in concert with the 'if' and 'exit' operators to count from 0 to 10 and to print the values as we count up.

The other looping operator is the forall operator which iterates over an array, adding each item to the operand stack each time through, then executing an executable array. Below is an example of using the 'forall' operator to print out an array:

Example 7-2. Walking an array with forall

[ 1 2 3 ] { print "\n" print } forall

Forall takes two operands off the operand stack. The first is the array to iterate over, the second is an executable array to invoke with each item. As each item is iterated over the item is pushed onto the operand stack. That's why the first 'print' works in the executable array in the previous example.

The 'exit' operand can also be used within a 'forall' construct. In the example below the code iterates through the array but breaks if the value is above 50:

Example 7-3. Using exit within forall

[ 1 2 3 10 20 30 100 200 300 ] {
 dup
 50 gt
 { exit } { print "\n" print } ifelse
} forall