colorForth Primer
Chuck Moore
colorForth is a uniquely simple way of programming computers. It is particularly suited to the multi-computer chips of GreenArrays. How simple it is:
Words
colorForth uses words much as English does. (A word can be a subroutine, if that helps.) A word is a string of lower-case characters (from a set of 48) ending with space. The character @ is pronounced fetch and fetches a number from some address. Likewise, ! (store) stores a number. Some words:
- and or drop dup over push pop
- for next unext -if if then
- ; @ ! @+ !+ @b !b @p !p
- + . +* 2* 2/ - b! a!
- 12345 -1 144 0
If you type a word, the computer will perform some action. For example
might turn on a light.
Numbers
Words that look like numbers are placed on a push-down stack (like a stack of dishes). @ also puts numbers on the stack. There they serve as arguments for later words:
Definitions
New words are defined in terms of old:
The red word is defined by the following green words. When you type toggle, the light is turned on, the computer waits 1000 ms (milliseconds) then turns it off. Semicolon marks the end of this word (return from subroutine).
Other words:
Here a number is stored into a register to change an output.
Loops
Computers are good at repetition. Here's one way to define a loop:
The word for expects an argument and puts it into a counter. The word next returns to for that many times. The word 1ms waits 1 millisecond.
Conditions
Computers sometimes need to make decisions:
abs will return the absolute value of its argument. If it is negative, -if does a ones-complement and adds 1. If it is not negative (positive or 0) -if jumps to then and does nothing.
Compiler
colorForth compiles source code into machine instructions, which can then be executed. It uses color to indicate the function of a word:
- Yellow - a word to be executed
- Red - a word being defined
- Green - a word to be compiled as part of a definition
- White (or black) - a comment to be ignored
Color aids understanding, avoids syntax and simplifies the compiler.
The compiler reads words from text stored in memory. A special editor manages this text. colorForth code is exceptionally compact.
Program
A program in colorForth is a collection of simple words that describe a task. Although definitions can be long and complicated, that is not wise. A larger number of simpler words is easier to read, write, debug and document.
The computer begs fallible programmers: Keep It Simple, Stupid (KISS). colorForth helps.