UniVerse Basic supports two forms of loop.
The first made its first appearance in traditional Dartmouth Basic: the FOR
/NEXT
loop:
FOR COUNTER = 10 TO 1 STEP -1 PRINT COUNTER NEXT COUNTER PRINT "Lift off!"
FOR
begins by setting the counter variable, imaginatively called COUNTER
, to the starting value of 10. The value is checked against the terminating TO
value of 1, and (as the STEP
to be added each time is negative) decides that the loop is not complete. Execution then passes to the next statement, which prints that value on the screen. The NEXT
statement simply returns execution to the head of the loop.
FOR
now adds the STEP
value to COUNTER
. In this case, the STEP
is -1, and so COUNTER
becomes 9. Again, it is compared to the TO
value, and again the loop continues.
This process repeats until COUNTER
reaches 1. FOR
compares the counter to the terminating value, and because it has not yet passed this value, the loop continues, and 1 is printed. NEXT
then returns execution to the FOR
statement. COUNTER
is incremented and reaches 0: this passes the terminating value, and so FOR
transfers control to the statement following the NEXT
, which in this case prints Lift off!
.
If you do not know how many times your loop will repeat, or it would require extra processing effort to find out the number of loops required in advance, you may be better off using a LOOP
/REPEAT
loop. A perpetual loop can be set up as follows:
LOOP PRINT 'Still looping...' REPEAT
This loop is perfectly legal, but will run for ever, which is not usually helpful. Usually you will want to specify some condition which will eventually terminate the loop. You can do this by using the UNTIL
statement:
COUNTER = 10 LOOP PRINT COUNTER UNTIL COUNTER = 1 COUNTER -= 1 REPEAT
Note that the UNTIL
can appear anywhere: not necessarily at the top or the bottom of the loop. This makes LOOP
/REPEAT
far more flexible than the choice of top-terminating or bottom-terminating loops offered by most other languages: though by making UNTIL
the first or last statement inside the loop you can emulate either.
You can use a WHILE
clause in place of an UNTIL
clause if you wish: WHILE
will continue the loop as long as the condition following it is true, whereas UNTIL
will continue as long as it is false. If follows that UNTIL condition
is logically identical to WHILE NOT(condition)
, and vice versa.
Choose the one which makes your condition read the most naturally. For instance, the the examples below, EOF
is an 'end of file' variable, while MORE.RECORDS
is a flag which indicates whether there are still records to process:
LOOP * Read from the file UNTIL EOF * Process the information read REPEAT LOOP * Read from the file WHILE MORE.RECORDS * Process the information read REPEAT