10.13Other Return Stack manipulations. 4tH 4tH Forth compiler
Reklaam
Reklaam
CHAPTER 10. INTEGER SEGMENT AND CODE SEGMENT 127
But we still have to be prepared that the word ’I’ will not provide the expected result
(which is the current value of the counter). In fact, ’I’ does simply copy the topmost value on the Return Stack. Which is usually correct, unless you’ve manipulated the Return Stack yourself.
Note that there are other words beside ’I’, which do exactly the same thing: copy the top of the Return Stack. But they are intended to be used outside a DO..LOOP. We’ll see an example of that in the following section.
10.13
Other Return Stack manipulations
The Return Stack can avoid some complex stack acrobatics. Stack acrobatics? Well, you know it by now. Sometimes all these values and addresses are just not in proper sequence, so you have to ’SWAP’ and ’ROT’ a lot until they are.
You can avoid some of these constructions by just moving a single value on the Return
Stack. You can return it to the Data Stack when the time is there. Or you can use the top of the Return Stack as a kind of local variable.
No, you don’t have to move it around between both stacks all the time and you don’t have to use ’I’ out of its context. There is a well-established word, which does the same thing:
’R@’. This is an example of the use of ’R@’:
: delete ( n )
>r #lag + ( a1) r@ #lag ( a1 a2 n2) r@ negate ( a1 a2 n2 n3) r# +!
#lead +
( a1 a2 n2)
( a1 a2 n2 a3) swap cmove ( a1) r> blanks ( --)
;
’R@’ copies the top of the Return Stack to the Data Stack. This example is taken from the
4tH-editor. It deletes "n" characters left of the cursor. By putting the number of characters on the Return Stack right away, its value can be fetched by ’R@’ without using ’DUP’ or
’OVER’. Since it can be fetched at any time, no ’SWAP’ or ’ROT’ has to come in.
10.14
Altering the flow with the Return Stack
The mere fact that return addresses are kept on the stack means that you can alter the flow of a program. This is hardly ever necessary, but if you’re a real hacker you’ll try this anyway, so we’d better give you some pointers on how it is done. Let’s take a look at this program.
Note that we comment on the Return Stack effects:
: soup ." soup " ;
: dessert ." dessert " ;
( r1 r2)
( r1 r6)
: chicken ." chicken " ;
: rice ." rice " ;
( r1 r3 r4)
( r1 r3 r5)
: entree chicken rice ; ( r1 r3)
: dinner soup entree dessert ; ( r1) dinner cr ( --)
And this is the output:
Laadi alla
Reklaam