Manipulating the parameter stack

Being a stack-based system, FlashForth must provide ways to put numbers onto the stack, to remove them and to rearrange their order. We've already seen that we can put numbers onto the stack by simply typing the number. We can also incorporate the number into the definition of a Forth word.


The word drop removes a number from the TOS thus making NOS the new TOS. The word swap exchanges the top 2 numbers. dup copies the TOS into NOS, pushing all of the other numbers down. rot rotates the top 3 numbers. These actions are shown below.

word executed     drop swap rot dup
             
stack result TOS
NOS
 -16
  73
   5
   2
  73
   5
   2
   5
  73
   2
   2
   5
  73
   2
   2
   5
  73

FlashForth also includes the words over, tuck and pick that act as shown below. Note that pick must be preceeded by an integer that (gets put on the stack briefly and) says where on the stack an element gets picked.
word executed     over tuck 3 pick
           
stack result TOS
NOS
 -16
  73
   5
   2
  73
 -16
  73
   5
   2
  73
 -16
  73
  73
   5
   2
  73
  73
 -16
  73
  73
   5
   2

From these actions, we can see that 0 pick is the same as dup, 1 pick is a synonym for over. The word pick is mainly useful for dealing with deep stacks, however, you should avoid making the stack deeper than 3 or 4 elements. If you are finding that you often have to reason about deeper stacks, consider how you might refactor your program.


Double length (32-bit) numbers can also be handled in FlashForth. A double number will sit on the stack as a pair of 16-bit cells, with the cell containing the least-significant 16-bits sitting below the cell containing the most-significant 16-bits. The words for manipulating pairs of cells on the parameter stack are 2dup, 2swap, 2over and 2drop. For example, we can put a double value onto the stack by including a period in the number literal.


hex 23. \fbox{$\hookleftarrow$} ok<$,ram>23 0



Note that memory on the PIC18 microcontrollers is limited and, for FlashForth, the parameter stack is limited to 48 cells.


Peter Jacobs 2013-06-12