12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- : foo ( n1 n2 -- )
- \ Show the data stack content.
- .s
- \ Take an element from the usual data stack and push it
- \ onto the return stack.
- >r
- \ Again show the data stack content. There should be one
- \ element less now on the data stack.
- .s
- \ Copy the top element of the return stack and push it
- \ onto the data stack.
- r@
- \ Pop one element of the data stack.
- .
- >r .s
- r@ .
- \ Move an element from the top of the return stack to the
- \ top of the data stack.
- r> .
- r@ .
- r> . ;
- \ When working with the return stack, for example to
- \ temporarily store data, it is important to clean up the
- \ return stack, before leaving the current
- \ definition. Otherwise the result is usually a crash.
- \ For example the following code from the tutorial:
- : crash ( n -- )
- >r ;
- 5 crash
- \ Results in something like the following error:
- \ :167: Invalid memory address
- \ 5 >>>crash<<<
- \ Backtrace:
- \ $7F50E6206A70 ;s
- \ Things pushed to the return stack inside a definition can
- \ only be accessed inside that definition.
- \ Also note, that in standard Forth it is not possible to
- \ mix usage of "locals" and the return stack.
- \ Assignment: Can you rewrite any of the definitions you
- \ wrote until now in a better way using the return stack?
- : true -1 ;
- : false 0 ;
|