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
/mod
performs a div-mod that splits a number into n%x
and n/x
1+
and 1-
saves a byte over 1 +
and 1 -
2*
and 2/
saves a byte over 2 *
and 2 -
- Double-cell words used on integers
d+
takes two four integers from the stack a b c d
and returns a+c b+d
m+
takes three integers from the stack a b c
and returns a+c b
Integer literals
- The
'c
prefix defines a number whose value is equal to the ASCII value of c
. This can save a byte on 3-digit integers (e.g. 100 -> 'd
)
- The
$
prefix denotes a hexadecimal integer, which may help on sufficiently large integer constants (e.g. 100 -> $64
)
- An integer literal with a decimal point on the end adds a zero to the stack (e.g.
9 0
-> 9.
)
Substitutions
UNDER+
is equivalent to m+
CELLS
is (usually) equivalent to 8 *
DROP
might be replaceable by +
, -
, *
, max
, or min
depending on what assumptions can be made about the top 2 values on the stack.
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"