Comments
Comments are used to document your code, and are passed over (ignored) by Forth. Comments in FlashForth are enclosed in brackets or preceded by a \ (backslash):
( Anything within brackets is a comment )
( Comments within brackets
can go over more than one line, but only when compiling )
\ Anything after a backslash is a comment, to the end of line
\ Backslash comments are single line only
Note the spaces before and after the opening bracket, and after the backslash. The bracket and backslash 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 when it doesn’t find them in the dictionary (word list), it will complain.
As well as documenting your code, 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:
As well as documenting your code, 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 the stack )
cr ( -- , prints a newline on the console )
Typically, stack diagrams are used within a word’s source code as a simple way of documenting the stack use and the purpose of a word. Here are some examples:
: kilobytes ( K -- BYTES, converts from kilobytes to bytes )
1024 *
;
: square ( A -- A*A, squares top of stack )
dup *
;
As stack diagrams are just comments, exactly how you specify the parameters is up to you, so long as it makes sense to you and to anyone else likely to read your code. For very simple and obvious words, stack diagrams are sometimes omitted.