16-return-stack.fth 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. : foo ( n1 n2 -- )
  2. \ Show the data stack content.
  3. .s
  4. \ Take an element from the usual data stack and push it
  5. \ onto the return stack.
  6. >r
  7. \ Again show the data stack content. There should be one
  8. \ element less now on the data stack.
  9. .s
  10. \ Copy the top element of the return stack and push it
  11. \ onto the data stack.
  12. r@
  13. \ Pop one element of the data stack.
  14. .
  15. >r .s
  16. r@ .
  17. \ Move an element from the top of the return stack to the
  18. \ top of the data stack.
  19. r> .
  20. r@ .
  21. r> . ;
  22. \ When working with the return stack, for example to
  23. \ temporarily store data, it is important to clean up the
  24. \ return stack, before leaving the current
  25. \ definition. Otherwise the result is usually a crash.
  26. \ For example the following code from the tutorial:
  27. : crash ( n -- )
  28. >r ;
  29. 5 crash
  30. \ Results in something like the following error:
  31. \ :167: Invalid memory address
  32. \ 5 >>>crash<<<
  33. \ Backtrace:
  34. \ $7F50E6206A70 ;s
  35. \ Things pushed to the return stack inside a definition can
  36. \ only be accessed inside that definition.
  37. \ Also note, that in standard Forth it is not possible to
  38. \ mix usage of "locals" and the return stack.
  39. \ Assignment: Can you rewrite any of the definitions you
  40. \ wrote until now in a better way using the return stack?
  41. : true -1 ;
  42. : false 0 ;