Inform 7 Home Page / Documentation


§11.10. Repeat

The other kind of loop in Inform is "repeat". The trouble with "while" is that it's not obvious at a glance when or whether the loop will finish, and nor is there any book-keeping to measure progress. A "repeat" loop is much more predictable, and is more or less certain to finish.

There are several forms of "repeat", of which the simplest is similar to the old FOR/NEXT loop from the home-computer programming language BASIC, for those with long memories:

repeat with (a name not so far used) running from (arithmetic value) to (arithmetic value)


or:   

repeat with (a name not so far used) running from (enumerated value) to (enumerated value):

This phrase causes the block of phrases following it to be repeated once for each value in the given range, storing that value in the named variable. (The variable exists only temporarily, within the repetition.) Example:

repeat with counter running from 1 to 10:
    ...

This, and runs through the given phrases ten times. Within those phrases, a special value called "counter" has the value 1 the first time through, then the value 2, then 3 and so on up to 10. (It can of course be called whatever we like: this is only an example.) The range can be from any kind where ranges make sense - anything on which arithmetic can be done, so for instance

repeat with moment running from 4 PM to 4:07 PM:
    ...

and also any enumeration:

Colour is a kind of value. The colours are red, orange, yellow, green, blue, indigo and violet.

...
    repeat with hue running from orange to indigo:
        ...

We are allowed to "nest" loops, that is, to put one inside another.

paste.png To plot a grid with size (S - a number):
    repeat with x running from 1 to S:
        say "Row [x]:";
        repeat with y running from 1 to S:
            say " [y]";
        say "."

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 if the Settings for the project are set to use the Z-machine, 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. (On Glulx, numbers can be very much larger.)


arrow-up.png Start of Chapter 11: Phrases
arrow-left.png Back to §11.9. While
arrow-right.png Onward to §11.11. Repeat running through

*ExampleWonka's Revenge
A lottery drum which redistributes the tickets inside whenever the player spins it.