OpenBoot 2.x Command Reference Manual

Creating Custom Definitions

Forth provides an easy way to create custom definitions for new command words. Table 4-3 shows the Forth words used to create custom definitions.

Table 4-3 Color Definition Words

Command 

Stack Diagram 

Description 

: new-name

( -- ) 

Start a new colon definition of the word new-name.

;  

( -- ) 

End a colon definition. 

Definitions for new commands are called colon definitions, 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 stored in local memory, which means they are erased when a system resets. To keep useful definitions, put them into a text file (using a text editor under your operating system or using the NVRAMRC editor). 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 

Every definition you create (in a text file) should have a stack effect diagram shown with that definition, even if the stack effect is nil ( -- ). This is vital because the stack diagram shows the proper use of that word. Also, use generous stack comments within complex definitions; this helps trace the flow of execution. For example, when creating add4, you could define it as:


: add4  ( n1 n2 n3 n4 -- )  + + + .  ; 

Or you could define add4 as follows:


: add4  ( n1 n2 n3 n4 -- )
   + + +  ( sum )
   .
; 


Note -

The ( (open parenthesis) is a Forth word meaning to ignore the following text up to ) (the closing parenthesis). Like any other Forth word, the open parenthesis must have one or more spaces following it.