Comments
Comments in Forth are enclosed in parentheses:
(Here is a comment)
Note the spaces before and after the parentheses. The parentheses are Forth words, and therefore the spaces are required. Leaving the spaces out will not work:
(This ISN'T a comment)
Forth will try to interpret (This, ISN'T, a, and comment) as individual words, and if it does not find them in the dictionary (word list), it will complain bitterly.
Comments are also used to specify stack diagrams. A stack diagram indicates the stack usage of a word, as well as what it does. The general format of a stack diagram specifies the parameters taken off the stack (N1), the parameters placed back on the stack (N2), and a comment indicating the purpose of the word:
wordname (N1 -- N2 , what this word does)
Here are stack diagrams for some common Forth words:
1+ (N -- N+1, increments the top of the stack) dup (N -- N N, duplicates the top of the stack) swap (A B -- B A, swap top two values on stack)
Typically, stack diagrams are used within a word definition as a simple way of documenting the stack use and purpose of a word. Here are some examples:
: helloworld (-- , says hi)
." hello world"
;
: square (A -- A*A , squares top of stack)
dup *
;Because stack diagrams are comments, exactly how you specify the parameters is up to you, just so long as it makes sense to you and to anyone else likely to read your code.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access