πŸ“Forth cheatsheet

tags

Forth

  • help

    • see <word> to show word definition

    • .S display stack without destroying it

  • I/O

    • . print number

    • emit show number as char

    • ." Hello" print string β€œHello” (space required after .")

  • Functions

    • : <funcname> <body...> ; define function

  • Variables

    • variable <varname> create variable

    • <varname> pushes variable address onto stack

    • <varname> @ fetch from variable

    • <value> <varname> ! store to variable

    • 2variable <varname> create double-length variable

  • Constants

    • <value> CONSTANT <constname> create constant

    • <constname> pushes value of the constant to the stack

  • Values (CORE EXTENSION)

    • <value> VALUE <valname> creates value and initializes it

    • <valname> push value to the stack

    • <value> TO <valname> re-assign value

  • Locals (LOCALS EXTENSION)

    • local variables

    • locals act as values (not variables)

    • LOCALS| a b c ... |

    • example

      : v+    ( a b c d -- a+c b+d)
          LOCALS| d c b a |
          a c +  b d +  ;
      
  • Return stack (rstack)

    • >R store to rstack

    • R> retrieve from rstack

    • R@ copy from rstack

  • Memory

    • @=/!= fetch/store numbers

    • D@=/=D! fetch/store double numbers

    • C@=/=C! fetch/store chars (chars are always positive)

    • CREATE <name> makes a new dictionary entry

    • HERE return address of the next available space

    • 13 CELLS ALLOT allocate 13 cells (kind of array) (used as in create x 10 cells allot)

  • Control flow

    • : test 0 = invert IF cr ." Not zero!" THEN ; if-then

    • : truth cr 0 = IF ." false" ELSE ." true" THEN ; if-then-else

    • recurse call itself

    • BEGIN xxx ( -- flag) UNTIL loop until flag is true

    • BEGIN xxx ( -- flag) WHILE yyy REPEAT loop until flag is false (execute yyy only if flag is true for given iteration)

    • <to> <from> DO ... LOOP (i can be used to get iteration number)

    • <to> <from> DO ... <step> +LOOP

    • ?DO skip looping if <to> and <from> are equal

  • create

    • CREATE is a component of the compiler, whose function is to make a new dictionary entry with a given name (the next name in the input stream)

    • : VARIABLE CREATE 1 CELLS ALLOT ; definition of variable

    • or : VARIABLE CREATE 0 , ;

    • , put top of stack to the dictionary pointer and increment dictionary pointer

    • : CONSTANT CREATE , DOES> @ ; definition of constant (it is usually implemented in machine code for speed, though)

    • DOES>

    • : : CREATE ] DOES> doLIST ; definition of :

    • : ; next [ ; IMMEDIATE definition of ;

    • [ switch to interpret mode, ] switch to compile mode

Backlinks