[Color Computer] [Coco] Bug in FOR NEXT ?

William Astle lost at l-w.ca
Thu Jun 1 18:50:57 EDT 2006


Arthur Flexser wrote:
> The bug occurs when you exit an initial FOR/NEXT loop without completing it
> (which is perfectly legal to do) and then reuse the same loop variable name in a
> later loop.  It is critical that the NEXT statements contain the variable name
> (i.e., NEXT Z, not just NEXT) for the bug to occur.  I think maybe the variable
> that was previously used in an inner loop must be used later in an outer loop,
> or possibly vice versa.  As I said, my memory is pretty vague on this, even
> though I did at one time trace the source of the bug in the ROM code.
> 
> Anyone want to fiddle around with coming up with some code that produces the
> spurious ?NF error?

I think I know how it occurs, based on my memory of reading the rom
code. It's a combination of two things, the first being the thing I
described in my other email (which rambled on about gosubs and
for/next). The second is what the code does when a for loop is started.
If I recall correctly, it does the following:

1. look for a FOR frame on the stack using the same variable
2a. if a frame was found, update the parameters and reuse the stack frame
2b. if a frame was not found, create a new one with the correct
parameters and push it onto the stack
3. go on with the execution of the program

Now, suppose you do the following:

10 FOR X = 1 TO 10
20 IF X = 4 GOTO 40
30 NEXT X
40 FOR Y = 1 TO 10
50 FOR X = 1 TO 10
60 NEXT X
70 NEXT Y

I suspect that you would get ?NF in line 70.

The reason is due to the operation of NEXT which is, IIRC, approximately
as follows:

1. search the stack for a FOR frame
2. if no frame found, ?NF error
3. if frame found, is it the requested variable? (always true for no
variable specified) If not, go back to 1
4. stack is now reset to point to the FOR frame that was found
5. apply the STEP to the variable and test the ending condition, etc
6. if loop is done, pop the FOR frame from the stack and resume at the
next statement after NEXT else resume execution after the FOR statement

So, as an artifact of reusing the FOR frame from the previous FOR X, the
order of the FOR frames on the stack is backwards so that when the NEXTX
executes, it removes the FOR frame for FOR Y from the stack.

My guess is that this was a (possibly) misguided attempt to avoid a
memory leak when an index variable is used repeatedly without the loop
ever running to completion.

-- 
William Astle
finger lost at l-w.net for further information

Geek Code V3.12: GCS/M/S d- s+:+ !a C++ UL++++$ P++ L+++ !E W++ !N w---
!D !M PS PE V-- Y+ PGP t+@ 5++ X !R tv+@ b+++@ !DI D? G e++ h+ y?



More information about the Coco mailing list