Wiki: Forth

Documentation

Look for all the useful words in the Gforth word index.

Boilerplate

The bye keyword is a necessary boilerplate to exit the Gforth interpreter. However, it is always shorter to replace bye with a random undefined word like a to trigger an error. This is the only mandatory 2-byte boilerplate.

However, whenever the code contains control structures such as if or loop, it must be used in a colon definition to avoid a compile error. Thus, it requires an 6-byte boilerplate:

: a do ... loop ; a

However, if your code contains less than four control structures, it is shorter to put square brackets around all control structures:

[do] ... [loop] ;

Looping

do ... loop

This is the most common looping construct. It takes the top two values from the stack and iterates over that interval. The index variable can be accessed with i, For example, this code prints the integers from 1 to 100:

101 1 do i . cr loop

A variation on this loop is ?do ... loop. It does the exact same thing, but does nothing if the start of the interval is greater or equal to the end of the interval. The standard do will instead loop forever, contrary to expectation.

for ... next

This loop behaves similarly to do ... loop. It takes the top value from the stack and iterates from that value to 0. For example, this code prints the integers from 100 to 0:

100 for i . cr next

Useful words

Integer literals

Substitutions

Strings

You can print a string using ." Hello" or put it on the stack using s" Hello" (There must be a space between the first double quote and the start of your string). To use backslash escapes inside a string literal, precede the first double quote with a backslash, e.g. .\" Hi\nBye" or s\" Hi\nBye"