LEGO MINDSTORMS Robots Manual page 113

Unofficial guide
Table of Contents

Advertisement

77 12 55
ok
. .
55 12 ok
.
77 ok
If you understand the stack, you know almost everything there is to know about Forth.
Words and the Dictionary
The other important concept in Forth is the dictionary. This is simply a list of words and what they mean. A word is a simply a program with a name. To run it,
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.
Built-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 see how this works:
77
ok
DUP
ok
. .
77 77 ok
Table 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 Words
Word
Meaning
DUP
Duplicates the top item on the stack
OVER
Copies the second stack item
PICK
Copies the
n
th stack item (
n
SWAP
Switches the top two stack items
ROT
Moves the third stack item to the top
DROP
Discards the top item on the stack
Forth also supports mathematical operators, which operate on the top two items of the stack and leave their result at the top of the stack. For example, you can divide two numbers like this:
84 2 /
ok
.
42 ok
Initial Stack
x1 x2
... n
is zero-based)
x1 x2
x1 x2 x3
Ending Stack
x
x x
x1 x2 x1
... xn
x2 x1
x2 x3 x1
x
Page 122

Hide quick links:

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the MINDSTORMS Robots and is the answer not in the manual?

Questions and answers

Table of Contents