Druzyek wrote:
Someone in the #forth channel on IRC showed me a way of handling local variables with what he called a "frame pointer." Here's an example:
Code:
: foo 3 { s1 @ s2 @ + s0 ! } 2drop ;
which is equivalent to this:
Code:
: foo + swap ! ;
3 { makes a copy of the data pointer, subtracts 3 cells from it, and saves it to the "frame pointer." s0 pushes the frame pointer to the stack, s1 pushes the frame pointer +1 cell etc. That way whatever is passed in on the stack as arguments can be frozen in place and accessed regardless of whatever else is on the stack as long as the rest of the word doesn't drop those first three items until it's done with them.
Obviously this is more trouble than it's worth for a short word like the one above, but it seems handy for a larger word with nested loops that need to access more than 3 items passed in.
Is this something that already exists in some forths?
Hmm! Would the code to handle these frames be different for different occasions?
I started writing something similar the same as PICK using R.
With any number of values ( n1 n2 .. nn -- ) pushed on the return stack, one could get numbers that are buried without popping a value off the stack with
"1 R, 2 R .. nR" . I dropped that idea when I needed to push something else on the return stack and it threw the order out the window. And also wanted to be able to carry a value back to the calling word.
I prefer using free zero page memory and on my computer, memory is free for Forth use from $0-$F. I use this area constantly as scratch pointers. Although one has to use @ or C@ to retrieve the value, the value does not have to be dropped when the definition is finished and the values can can also be carried back to the calling word.