Stack manipulation commands (described in Table 4-3) allow you to add, delete, and reorder items on the stack.
Table 4-3 Stack Manipulation Commands|
Command |
Stack Diagram |
Description |
|---|---|---|
| clear |
( ??? -- ) |
Empty the stack. |
| depth |
( ... -- ... u ) |
Return the number of items on the stack. |
| drop |
( x -- ) |
Remove top item from the stack. |
| 2drop |
( x1 x2 -- ) |
Remove 2 items from the stack. |
| 3drop |
( x1 x2 x3 -- ) |
Remove 3 items from the stack. |
| dup |
( x -- x x ) |
Duplicate the top stack item. |
| 2dup |
( x1 x2 -- x1 x2 x1 x2 ) |
Duplicate 2 stack items. |
| 3dup |
( x1 x2 x3 -- x1 x2 x3 x1 x2 x3 ) |
Duplicate 3 stack items. |
| ?dup |
( x -- x x | 0 ) |
Duplicate the top stack item if it is non-zero. |
| nip |
( x1 x2 -- x2 ) |
Discard the second stack item. |
| over |
( x1 x2 -- x1 x2 x1 ) |
Copy second stack item to top of stack. |
| 2over |
( x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2 ) |
Copy second 2 stack items. |
| pick |
( xu ... x1 x0 u -- xu ... x1 x0 xu ) |
Copy u-th stack item (1 pick = over). |
| >r |
( x -- ) (R: -- x ) |
Move a stack item to the return stack. |
| r> |
( -- x ) ( R: x -- ) |
Move a return stack item to the stack. |
| r@ |
( -- x ) ( R: x -- x ) |
Copy the top of the return stack to the stack. |
| roll |
( xu ... x1 x0 u -- xu-1 ... x1 x0 xu ) |
Rotate u stack items (2 roll = rot). |
| rot |
( x1 x2 x3 -- x2 x3 x1 ) |
Rotate 3 stack items. |
| -rot |
( x1 x2 x3 -- x3 x1 x2 ) |
Inversely rotate 3 stack items. |
| 2rot |
( x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2 ) |
Rotate 3 pairs of stack items. |
| swap |
( x1 x2 -- x2 x1 ) |
Exchange the top 2 stack items. |
| 2swap |
( x1 x2 x3 x4 -- x3 x4 x1 x2 ) |
Exchange 2 pairs of stack items. |
| tuck |
( x1 x2 -- x2 x1 x2 ) |
Copy top stack item below second item. |
A typical use of stack manipulation might be to display the top stack item while preserving all stack items, as shown in this example:
5 77 ok dup (Duplicates the top item on the stack) 5 77 77 ok . (Removes and displays the top stack item) 77 5 77 ok