Creating New Words

A new word is created by using a colon definition . An example of this is shown in Figure 3-1. This simple program prints "A" to the console.

Colon definition

Figure 3-1. Colon definition

The colon (:) tells the compiler that a definition is starting, and that what comes next is the name of the word, in this case "fred." The definition is finished with a semicolon ( ;), the equivalent of a return in C or assembler. Everything in between : and ; constitutes the new program. In this example, the decimal value of 65 (the ASCII code for "A") is loaded onto the stack, and then the word emit is called. To run our new word, we simply type fred at the prompt. To run fred three times, we simply type fred fred fred at the prompt.

Forth uses threaded code , which is a list of subroutine identifiers (words). Each word within a program is called in turn, thus producing the sequence of running code. The interpreter is responsible for calling words as appropriate and is capable of only three operations. The first of these is the call , which, as the name implies, begins execution of a given word. The second operation is known as the next operation and passes control from one word to the next word in the list. The return operation passes control back to the calling list of words. The call is often known as nesting , and the return is known as unnesting . As a consequence of this structure, ...

Get Designing Embedded Hardware, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.