Page 133 - The Unofficial Guide to Lego Mindstorms Robots
P. 133
122
you just type its name. Many programs expect to find input values on the stack and may place their results on the stack when
they're done.
Bu ilt-in words
Forth has a number of simple words that are built in to the dictionary. DUP, for example, duplicates the top element of the
stack. You can easily s ee how this works:
77
ok
DUP
ok
. .
77 77 ok
T able 6-2 lists some of the important built-in words in Forth. The table shows the stack before ("Initial Stack") and after
("Ending Stack") the word runs. By convention, the top is shown on the right. For example, x1 x2 shows a stack with x2 at
the top and x1 as the second item. This seems confusing at first, but it makes sense after a while (and it's the convention in
Forth documentation).
Table 6-2. Forth Built-in Wor ds
Word Mean ing Initial Stack Ending Stack
DU P Duplicates the top item on the stack x x x
O VER Copies the second stack item x1 x2 x1 x2 x1
PICK Copies the nth stack item (n is zero-based) … n … xn
SWAP Switches th e top two stack items x1 x2 x2 x1
R OT Moves the third stack item to the top x1 x2 x3 x2 x3 x1
DROP Disca rds the top item on the stack x
Forth also supports mathematical operators, which operate on the top two items of the stack and leave their result at the top of
ac
the st k. For example, you can divide two numbers like this:
84 2 /
ok
.
42 ok
Bitwise operators are also defined: AND, OR, XOR.
You can change the number base you're working in using the HEX and DECIMAL words. For example, if you wanted to work
in hexidecimal (base 16), you would type HEX. Base 10 is represented by DECIMAL. Most of the numbers in this chapter will
be base 16.