dup
Duplicates the number on top of the integer stack, to use it twice without reading or computing it again.
Facts
- Word
dup- Aliases
dupint- Family
- Basic
- Integer stack
- pops 1, pushes 2
- What it does
- Copies the top: a becomes a a. With an empty stack it pushes two zeros.
- Cost
- Basic command
- Runs
- inside a gene: in the condition (cond) and in the body (start or else)
a dup leaves a a. It is useful when a value is needed twice: instead of reading the cell again or repeating the calculation, you copy it. You can also write dupint.
| Word | Stack after |
|---|---|
*.eye5 | 40 (for example) |
dup | 40 40 |
mult | 1600 |
This bot stores in cell 50 what the central eye (.eye5) sees squared, and in cells 51 and 52 what it sees plus 10, computed only once:
cond
start
*.eye5 dup mult 50 store
*.eye5 10 add dup 51 store 52 store
stopThe other famous use is in the Bestiary: x dup div is 1 if x is not zero and 0 if it is, because div by zero gives 0. With that you build conditions out of pure arithmetic (see Operators by family).
An inherited quirk: with an empty stack, dup does not leave the stack empty but pushes two zeros. dupbool, its counterpart on the boolean stack, does nothing with an empty stack.