A do loop (also called a counted loop) is used when the number of iterations of the loop can be calculated in advance. A do loop normally exits just before the specified ending value is reached.
Table 4-31 lists commands to control the execution of counted loops.
Table 4-31 do (Counted) Loop Commands
Command |
Stack Diagram |
Description |
---|---|---|
+loop |
( n -- ) |
End a do+loop construct; add n to loop index and return to do (if n < 0, index goes from start to end inclusive). |
?do |
( end start -- ) |
Begin ?doloop to be executed 0 or more times. Index goes from start to end-1 inclusive. If end = start, loop is not executed. |
?leave |
( flag -- ) |
Exit from a doloop if flag is non-zero. |
do |
( end start -- ) |
Begin a doloop. Index goes from start to end-1 inclusive. Example: 10 0 do i . loop (prints 0 1 2...d e f). |
i |
( -- n ) |
Leaves the loop index on the stack. |
j |
( -- n ) |
Leaves the loop index of the next outer enclosing loop on the stack. |
leave |
( -- ) |
Exit from doloop. |
loop |
( -- ) |
End of doloop. |
The following screen shows several examples of how loops are used.
ok 10 5 do i . loop 5 6 7 8 9 a b c d e f ok ok 2000 1000 do i . i c@ . cr i c@ ff = if leave then 4 +loop 1000 23 1004 0 1008 fe 100c 0 1010 78 1014 ff ok : scan ( byte -- ) ] 6000 5000 (Scan memory 5000 - 6000 for bytes not equal to the specified byte) ] do dup i c@ <> ( byte error? ) ] if i . then ( byte ) ] loop ] drop ( the original byte was still on the stack, discard it ) ] ; ok 55 scan 5005 5224 5f99 ok 6000 5000 do i i c! loop (Fill a region of memory with a stepped pattern) ok ok 500 value testloc ok : test16 ( -- ) 1.0000 0 ( do 0-ffff ) (Write different 16-bit values to a location) ] do i testloc w! testloc w@ i <> ( error? ) (Also check the location) ] if ." Error - wrote " i . ." read " testloc w@ . cr ] leave ( exit after first error found ) (This line is optional) ] then ] loop ] ; ok test16 ok 6000 to testloc ok test16 Error - wrote 200 read 300 ok