docs/forth-cheatsheet.txt (2019 bytes)
1 FORTH CHEAT SHEET (our own kernel, STM32F446 on QEMU netduinoplus2) 2 ===================================================================== 3 Forth reads words left to right. Numbers go on the stack. Words 4 eat from the stack and push results. ".s" shows the stack. 5 Editing: Backspace and Delete both erase the last character. 6 7 STACK 8 1 2 3 .s show stack -> 1 2 3 9 . u. print and drop top 5 . -> 5 10 dup drop swap over rot -rot nip tuck pick ?dup 2dup 2drop depth 11 >r r> r@ rdrop move items to/from the return stack 12 13 ARITHMETIC (32-bit integers) 14 + - * / mod /mod u/mod m* um* 17 5 /mod . . -> 3 2 15 negate abs min max 1+ 1- 2+ 2- 2* 2/ cells cell+ 16 hex decimal hex FF decimal . -> 255 also $FF #10 %101 17 18 COMPARE AND LOGIC (true = -1, false = 0) 19 = <> < > <= >= u< u> 0= 0<> 0< 0> 20 and or xor invert bic lshift rshift arshift 21 22 DEFINE WORDS 23 : sq ( n -- n*n ) dup * ; 7 sq . -> 49 24 ( ... ) comment \ comment to end of line words lists every word 25 immediate recurse literal [ ] ' ['] [char] execute 26 27 CONTROL FLOW (inside : ... ;) 28 : sign dup 0< if ." neg" else ." pos" then drop ; 29 : count10 10 0 do i . loop ; -> 0 1 2 ... 9 30 : evens 10 0 do i . 2 +loop ; -> 0 2 4 6 8 31 : down begin dup . 1- dup 0= until drop ; 5 down -> 5 4 3 2 1 32 begin ... while ... repeat begin ... again ?do leave unloop i j 33 34 VARIABLES AND MEMORY 35 42 variable x initial value comes FIRST x @ . -> 42 36 7 x ! 5 x +! 42 constant answer 16 buffer: buf 37 @ ! c@ c! h@ h! +! bis! bic! cbis! cbic! move fill compare count 38 here allot , c, align unused type emit key key? cr space 39 s" text" type ." text" (s" also works at the prompt) 40 41 TRY THESE 42 : fib ( n -- f ) 0 1 rot 0 ?do over + swap loop drop ; 10 fib . -> 55 43 : stars 0 ?do 42 emit loop ; 5 stars -> ***** 44 : fact ( n -- n! ) 1 swap 1+ 1 ?do i * loop ; 6 fact . -> 720 45 46 QUIT: Ctrl-C stops QEMU. Words you define live in RAM and are lost.