![]() | Chapter 11: Phrases | ![]() ![]() |
11.9. Repeat |
The following kind of loop could if necessary be achieved just as well with a suitable "while", but occurs so often that it is convenient to have a standard form. Repeat loops also have the great advantage of being certain to finish.
repeat with my counter running from 1 to 10 begin;
(phrases)
end repeat;
This is similar to the old FOR/NEXT loop from BASIC, for those with long memories, and runs through the given phrases ten times. Within those phrases, a special value called "my counter" has the value 1 the first time through, then the value 2, then 3 and so on up to 10. This value exists only within the loop, so it makes no sense to talk about "my counter" elsewhere. (It can of course be called whatever we like: this is only an example.)
The "begin" and "end repeat" are compulsory for repeat loops, in the interests of clarity.
We are allowed to "nest" loops, that is, to put one inside another.
To plot a grid with size (S - a number):
repeat with x running from 1 to S begin;
say "Row [x]:";
repeat with y running from 1 to S begin;
say " [y]";
end repeat;
say ".";
end repeat.
If we then write
plot a grid with size 5
then the result is
Row 1: 1 2 3 4 5.
Row 2: 1 2 3 4 5.
Row 3: 1 2 3 4 5.
Row 4: 1 2 3 4 5.
Row 5: 1 2 3 4 5.
Thus the innermost phrase, the say which mentions "y", happens 25 times.
Whenever dealing with numbers in Inform we may need to remember that the range is restricted to -32768 up to 32767. Repeating with a counter up to exactly 32767 is hazardous, because the counter can never break through this barrier: it's infinity, so far as Inform is concerned, and that can cause the repetitions to go on forever.
| ![]() A lottery drum which redistributes the tickets inside whenever the player spins it. |
|
Previous | Contents | Next |