Page 134 - The Unofficial Guide to Lego Mindstorms Robots
P. 134

123


          BASE is a word (a variable, which I'll talk about soon) that contains the current number base. To print out the current number
          b ase, for example, do this:

              BASE @ .
              10 ok

          Interestingly, the current base is printed in terms of the current base, so it will always be 10. Suppose you're working in base 8.
          If you print out the current base, 8, in base 8, it's expressed as 10. Retrieving  the current base with BA SE @ may  seem like a
          p ointless exercise, but it's useful if you want to save the current base away to be restored at some later time.

          If  you want to work in a number system other than HEX or DECIMAL, you can use BASE ! to store any base number. The
          following example s hows two ways you can use Forth to convert numbers between different bases:

              HEX 20 DECIMAL . (20 in base 16 is 32 in base 10)
                  32 ok
              8 BASE ! 20 DECIMAL . (20 in base 8 is 16 in base 10)
                  16 ok

          The open p arenthesis ( is used to indicate a comment. The pbFORTH interpreter simply ignores the rest of the line after it
          se es the (.

          D efin ing words

          W riti ng programs in Forth is a matter of defining your own words in the dictionary. Word definitions begin with a colon and
          end with a semicolon. Here's a simple example:

              : threeTimes DUP DUP + + ;
              ok

          The colon tells the Forth interpre ter that the words that follow define a new word for the dictionary and should be stored to run
          later. The new word n eeds a nam e, threeTimes in this example, which is supplied immediately after the colon. Subsequent
          words wil l be execute d when the new word is executed. The semicolon tells the interpreter that the new word definition has
          ended. three Times duplicates the top item on the stack twice, so there are three copies of it, then adds them all together.
          Now that you've defined a new word, you can use it like any other Forth word:

              5 threeTimes .
              15 ok

          A nd you can, of course, use it in subsequent definiti ons:

              : nineTimes threeTimes threeTimes ;
              ok
              5 nineTimes .
              45 ok
   129   130   131   132   133   134   135   136   137   138   139