| A Gentle Introduction to Forth | ||
| Links gForth Tutorial |
If you ever used an HP calculator (or a slide
rule) Forth will seem like a great idea. If you haven't, it is still a
great idea, you just don't know it yet! Forth operates on a stack. Forget PIC Forth for a second, let's just look at gForth so you can get an idea about how Forth in general works. If you run gForth, you will be expected to type something in. Try this: 5 5 + . The spaces are important (although the number of spaces isn't). This line tells Forth to push 5 on the stack, then push another 5 on the stack. The + word asks Forth to add the two numbers at the top of the stack producing a new value on the stack (and consuming the two values). The dot tells Forth to print the top of the stack (and remove the element). So at the end of this line, Forth prints 10 and has an empty stack. If you enter another dot command (.) you will get an error message. Just hit enter to dismiss it. Every command is Forth is a word which is nothing more than a sequence of characters that don't contain white spaces. So 5, 5, +, and . are all words. The above could be written: 5 Any space character will do. You can't write "5 5+ ." because that uses a different word, 5+. There probably isn't a 5+ word defined, but you could define it yourself. You can define words like ** or !x! that would not be legal identifiers in most languages. Comments in Forth start with a ( and end with a ) or run from a \ to the end of the line. Don't forget to make these words: ( this is a comment ) (this is not a comment) ( this starts out ok but ends badly) \ from here to the end of line is a comment \this isn't a comment, but a bunch of words starting with \this The real power to Forth is that you can define your own words. PIC Forth has a 2* word that shifts a word to the left, and therefore multiplies it by two. Suppose you want to write 5* which multiplies by 5. You know that 5x = 4x+x and that equals 2x + 2x +x. So you can define a new word by using a colon: : 5* dup 2* 2* + ; The semicolon ends the definition. The dup word duplicates the top of the stack. It is customary to include a comment that explains the state of the stack before and after the word executes (although this is just a convention): : 5* ( x -- 5*x ) dup 2* 2* + ; A complete tutorial on Forth isn't my objective. You can find a link to the gForth tutorial to the left. However, keep in mind that PIC Forth won't support all the things you can do in gForth. One big difference is that PIC Forth's stack contains bytes. There is no interactive execution mode. Numbers are in hex by default. For learning, you might want to stay in gForth (or execute the forth word in PIC Forth to switch modes). In the next frame, we'll start working with PIC Forth.
|