Stack Manipulation Operations
Learn how to manipulate the stack directly in your programs.
Reference
Name | Operation | Stack notation | Description |
Duplicate | dup | ( a -- a a ) | Duplicates the top item of the stack. |
Drop | drop | ( a -- ) | Removes the top item from the stack. |
Swap | swap | ( a b -- b a ) | Swaps the top two items on the stack. |
Over | over | ( a b -- a b a ) | Copies the second item on the stack to the top. |
Rotate | rot | ( a b c -- b c a ) | Rotates the top three items on the stack, moving the third item to the top. |
Usage
Use stack manipulation operations to manage data flow in your programs. Here are a few examples:
# Duplicating the top item
5 dup # The stack now contains: 5 5
# Dropping the top item
10 20 drop # The stack now contains: 10
# Swapping two items
7 9 swap # The stack now contains: 9 7
# Using over to duplicate the second item
3 6 over # The stack now contains: 3 6 3
# Rotating the top three items
1 2 3 rot # The stack now contains: 2 3 1