6.9.4 Begin loops with multiple exits

For counted loops, you can use leave in several places. For begin loops, you have the following options:

Use exit (possibly several times) in the loop to leave not just the loop, but the whole colon definition. E.g.,:

: foo
  begin
    condition1 while
      condition2 if
        exit-code2 exit then
      condition3 if
        exit-code3 exit then
    ...
  repeat
  exit-code1 ;

The disadvantage of this approach is that, if you want to have some common code afterwards, you either have to wrap foo in another word that contains the common code, or you have to call the common code several times, from each exit-code.

Another approach is to use several whiles in a begin loop. You have to append a then behind the loop for every additional while. E.g.,;

begin
  condition1 while
    condition2 while
      condition3 while
again then then then

Here I used again at the end of the loop so that I would have a then for each while; repeat would result in one less then, but otherwise the same behaviour. For an explanation of why this works, See Arbitrary control structures.

We can have common code afterwards, but, as presented above, we cannot have different exit-codes for the different exits. You can have these different exit-codes, as follows:

begin
  condition1 while
    condition2 while
      condition3 while
again then exit-code3
else exit-code2 then
else exit-code1 then

This is relatively hard to comprehend, because the exit-codes are relatively far from the exit conditions (it does not help that we are not used to such control structures, either).