PDA

View Full Version : Getting out of indefinite loops


JimB
08-17-06, 02:53 PM
I have a fairly complex control scheme that I've written in "Max-Forth 3.3" for use in a NMIX-0021/22 board. Things got difficult when I needed to get out of an indefinite loop (BEGIN --- UNTIL) more than one time. What I needed was a "goto" statement. The following generic code will show that I wound up using a DO --- LOOP that only runs once. This allows the use of (LEAVE) any number of times. The DO, LOOP was then nested inside of BEGIN, UNTIL. Maybe someone will think its dumb but I thought it was cool. Hope this will help someone.
Jim

: CK#1 --- ; ( --- flag )
: CK#2 --- ; ( --- flag )
: DO#1THING --- ;
: DO#2THING --- ;
: SUB1 DO#3THING ;

: SUB2 1 0 DO
CK#1 IF DO#1THING
ELSE CK#2 LEAVE
THEN
IF DO#2THING (this picks up flag on stack left by CK#2)
ELSE SUB1 LEAVE
THEN
LOOP ;

: MAIN BEGIN SUB2 ?TERMINAL UNTIL ;

RMDumse
08-17-06, 03:40 PM
Yes, that is exactly the problem with structured languages. In order to make some escapes from deeply embedded loops work, you need to add a bit of state information to get out of the loops, then get to going where you need to outside the loops. Often people solve this by adding this state information explicitly. They add a GET_OUT flag, for instance, to their BEGIN UNTIL loops. And of course the DO LOOPs have their LEAVE escape.

You've chosen to put this state information in variables left on the stack and have a two part put on stack, strip from stack, set of words.

It was experiencing the need for these kinds of structures that drove me to create IsoMax(TM), the state based extension of Forth, that handles state information more explicitly as being what it is, state information. It's a bit different programming paradigm, but it gives some surprizing results.

Thanks for your post.