Forth provides an easy way to create new command words from sequences of existing words. Table 4-4 shows the Forth words used to create such new words.
Table 4-4 Colon Definition Words
Command |
Stack Diagram |
Description |
---|---|---|
: new-name |
( -- ) |
Start a new colon definition of the word new-name. |
; |
( -- ) |
End a colon definition. |
This kind of word is called a colon definition, named after the word that is used to create them. For example, suppose you want to create a new word, add4, that will add any four numbers together and display the result. You could create the definition as follows:
ok : add4 + + + . ; ok
The ; (semicolon) marks the end of the definition that defines add4 to have the behavior (+ + + .). The three addition operators (+) reduce the four stack items to a single sum on the stack; then . removes and displays that result. An example follows.
ok 1 2 3 3 + + + . 9 ok 1 2 3 3 add4 9 ok
Definitions are forgotten if a machine reset takes place. To keep useful definitions, put them into the script or save them in a text file on a host system. This text file can then be loaded as needed. (See Chapter 5, Loading and Executing Programs for more information on loading files.)
When you type a definition from the User Interface, the ok prompt becomes a ] (right square bracket) prompt after you type the : (colon) and before you type the ; (semicolon). For example, you could type the definition for add4 like this:
ok : add4 ] + + + ] . ] ; ok
The above use of ] while inside a multi-line definition is a characteristic of Sun's implementation.
The stack diagram shows proper use of a word, so include a stack diagram with every definition you create, even if the stack effect is nil ( -- ) . Use generous stack comments in complex definitions to trace the flow of execution. For example, when creating add4, you could define it as:
: add4 ( n1 n2 n3 n4 -- ) + + + . ;
Or you could define it as follows:
: add4 ( n1 n2 n3 n4 -- ) + + + ( sum ) . ( ) ;
The "(" is a Forth word meaning ignore the text up to the ")". Like any other Forth word, the "(" must have one or more spaces after it.