More Loops
Skipping index
You can skip an index using the word +LOOP
: skip5 25 0 do i . 5 +LOOP ; skip5should display
0 5 10 15 20 ok
Note that 25 is not printed, even though it equals to the end index.
However, if the skip is negative, i.e., counting down. You get the end index.
: skip5down 0 25 do i . -5 +loop ; skip5downshould display
25 20 15 10 5 0 ok
Stopping a DO...LOOP
To stop aDOloop use the words
LEAVEand
UNLOOP:
LEAVE
simply leaves the loop, and executing continues after LOOP- The pair
UNLOOP EXIT
must be used if you want to exit the word completely.
Some examples:
: short 100 0 do i dup . 2 = if LEAVE then loop "Hello!" . ; shortwill display
0 1 2 Hello! ok
Another example:
: never-ever 100 0 do i dup . 2 = if UNLOOP exit then loop "I will never be printed!" . ; never-everwill only print
0 1 2 ok
Be sure you try out these examples and thoroughly understand them before moving on!
Quiz
Question 1
What do you think would happen if we changed the 100 0 inSHORTto 100 2 ? Try to guess the answer then experiment with the Smojo Terminal.
: short 100 2 do i dup . 2 = if LEAVE then loop "Hello!" . ; shortThis will print
2 Hello! ok
Question 2
What do you think would happen if we changed the LOOP inNEVER-EVERto 5 +LOOP ? Guess the answer then check with the Terminal.
: never-ever 100 0 do i dup . 2 = if UNLOOP exit then 5 +loop "I will never be printed!" . ; never-everThis will print
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 I will never be printed! ok