Program Flow: Repeating instructions until something happens

The final loop type that PureBasic offers is the Repeat...Until loop (I am sure you can guess where the name came from by now :). This type of loop can be thought of as the opposite of the While...Wend loop, although both could be used for the same purposes. The basic structure of the Repeat...Until loop is shown below:
Repeat
    ; Instructions to execute during the loop
Until <expression>

The operation of a Repeat...Until loop is that the instructions inside the loop are executed and then the value of the expression is calculated. If this value is true then the loop exits and the program continues executing from the next instruction after the Until keyword. If the value of the expression is false then the loop repeats. The overall working of this loop can be thought of as repeating a sequence of instructions until something happens. Notice that the instructions inside the loop are always executed at least once.

The examples below different ways to use the Repeat...Until loops, which you can also download from here.

If OpenConsole()

    divided.l = 64
    Repeat
        PrintN("divided = "+Str(divided))
        divided = divided / 2
    Until divided = 1

    Repeat
        PrintN("You will see this once")
    Until 1

    PrintN("Press return to exit")
    Input()
    CloseConsole()
EndIf
End

Output from the Repeat...Until loop example As you can see from the example output on the right, the last variable value to be printed is 2. This is because the value is printed and then divided by 2 (giving 1). The Repeat loop exits when the value of the variable is 1, and because the expression check is performed at the end of the loop, it is exited here.

The second Repeat...Until loop in that example shows the position that the expression is checked. The loop exits when the expression, 1, is true (and since 1 is non-zero it is true, meaning that the loop will exit on the first iteration). As you can see from the example output, the print instruction is executed before the loop is exited meaning that the expression check must come after the PrintN command, i.e. at the end of the loop. This is the opposite from the While...Wend loop.

Forever keyword

There is an alternative to using the Until keyword and that is to use the Forever keyword. It does not require an expression since its use is to make the loop repeat forever. If you use this keyword in a Repeat loop then you will need to use one of the techniques described on the next page to get out of the loop.