Math

Stack manipulation

Working with Files

Comments

Compiling words

By convention the comment after the name of a definition describes the stack effect: The part in front of the '--' describes the state of the stack before the execution of
the definition, i.e., the parameters that are passed into the colon definition; the part behind the '--' is the state of the stack after the execution of the definition,
i.e., the results of the definition. The stack comment only shows the top stack items that the definition accesses and/or changes.

You should put a correct stack effect on every definition, even if it is just ( -- ). You should also add some descriptive comment to more complicated words (I usually do
this in the lines following :). If you don't do this, your code becomes unreadable (because you have to work through every definition before you can understand any).

Conventions for stack effect comments

(De)Compiling words

: squared ( n -- n^2 ) \ The parenthesis are just a convention to explain the function.
  dup * ;

"Types"

Forth doesn't do any type checking whatsoever. It's not a big deal though, but you should be aware of it.

Locals (Local variable definitions)

Curly braces in a word definition allow you to create local variables in the definition.

: swap { a b -- b a }
b a ;

Conditionals

Conditionals can only be used within a colon definition.

 : abs ( n1 -- +n2 ) 
   dup 0 < if
   negate
 endif ;

NOTE: In Forth, endif is less commonly used. Typically, the word then is used. But that's really confusing for non-forth programmers.

Another example:

: min ( n1 n2 -- n )
 2dup < if 
  drop
 else
  nip
endif;

Boolean expressions

Loops

 : endless ( -- )
   0 begin
     dup . 1+
   again ;
 endless

use leave to get out of a loop and exit to leave the definition.

Recursion

Use recurse to call the word being defined.

The Return Stack

Aside from the main stack ('the stack'), there is also a 'return stack'. Typically, the return stack is used to store temporary variables. Miscounting items on the return stack usually causes a crash

Memory and Global Variables

Working with Floating Point Numbers

Write floats with scientific notation.

1.23e -> 1.23 1e0 -> 1.0

Most Forth implementations create a seperate stack for FP operations. This includes Gforth. Usually, you can just prefix data stack operators with an 'f' to operate in the float stack. Eg: f. to pop off the fp stack. Other operators include f+ f- f* f/ f** f@ and f!.