Page 135 - The Unofficial Guide to Lego Mindstorms Robots
P. 135
124
Here's another simple example that demonstrates how to print messages from within a word. Be careful about the spacing: the
actual string to be printed is framed by the .“ and ” words, which
ar e separate from the string.
: helloWorld ." Hello, world. " ;
ok
helloWorld
Hello, world. ok
If you define a word that already exists, it will be redefined:
: helloWorld ." Tag, Welt. " ;
redefine he lloWorld ok
Constants and Variables
You can define words in Forth that represent numerical values. These words are called constants; you can use the word
anywhere you really m ean the number it represents. This is really handy for making programs more readable. To define a
constant, push its value on the stack. Then use the word CONSTANT and supply a name. like this:
7 CONSTANT FULL
ok
You can the use FULL anywhere you really mean 7, like this:
FULL 2 0 MOTOR_ SET
ok
V ariables are even easier to define. Just use the word VARIABLE and supply a name:
VARIABLE z
ok
Values are stored in variables using the ! word, pronounced "store":
12 z !
o k
T he value of a variable can be retrieved and placed on the s tack with the @ word:
z @ .
12 ok
There's some tricky stuff going on here that I'll briefly discuss. A variable is really an address in memory. The ! word expects
t o find an address and a value on the stack; it stores the value a t the specified address. Similarly, the @ word expects to find an
a ddress on the stack. It replaces the address with the value at that address. When you declare a variable with the VARIABLE
w ord, all you're really doing is assigning an address (determined by the Forth interpreter) to a name.