Programming in Forth
Last updated
Last updated
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.
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.
In forth a function definition starts with a :
and ends with a ;
. Here's an example of a function square
that squares a number:
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.
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.
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.
Word
Signature
Description
.
a -- a
Prints an integer a
to standard output
+
a b -- c
Adds two integers
-
a b -- c
Subtracts two integers
*
a b -- c
Multiplies two integers
/
a b -- c
Divides two integers (a / b)
=
a b -- c
Checks if two integers are equal.
<=>
a b -- c
Compares two integers.
if a > b then -1
if a = b then 0
if a < b then 1
>
a b -- c
Is a > b?
<
a b -- c
Is a < b?
!
a b -- a b
Sets the memory referenced by pointer b
to a
@
a -- a b
Gets the value referenced by pointer a
c@
a -- a b
Gets the byte referenced by pointer a
drop
a --
Drops the top of the stack
dup
a -- a a
Duplicates the top of the stack
tuck
a b c -- a c b c
Duplicates the top of the stack under the second item
swap
a b -- b a
Swaps the top two stack items
third
a b c -- a b c a
Duplicates the third stack item to the top
puts
a -- a
Prints the string referenced by pointer a
to standard output
spaces
a --
Prints a
spaces to standard output
true
-- 1
Evaluates to 1
false
-- 0
Evaluates to 0