Programming in Forth

Unlike most other languages, Forth is a stack based language. This means that nearly everything is done on the stack. You can think of the stack as a stack of paper, you can put papers on it and take sheets off the top. You can't access things at any position in the stack, only items from the top. There are functions (called words in forth) that modify the stack for you.

Comments

Line comments in forth start with a \ and go until the end of the line. Block comments start with ( and end with ). They can be nested

Windows style (\r\n) line endings should work fine, but if any issues occur try switching to Unix line endings. Very old Macs that use only \r will probably not work.

Functions

In forth a function definition starts with a : and ends with a ;. Here's an example of a function square that squares a number:

: square dup * ;

In forth it is customary to describe the stack modifications done by a function. This is done in a block comment right after the name of the function.

: square ( a -- b )
    dup *
;

The -- separates the descriptions of the stack before and after the function is run. On the left there is a, a variable consumed by the function. On the right, there is b, the result of the function.

Basic Words

Functions and variables in forth are called words. The square function that was defined in the previous section is a word, just like dup and *. Calling a word is as simple as just typing it's name. Here is a list of basic forth words. Some of these are different from other forth implementations.

Last updated