Compiling from Files |
Forth can read read from ordinary text files so you can use any editor that you
wish to write your programs.
A D V E R T I S E M E N T
Sample Program
Enter into your file, the following code.
\ Sample Forth Code
\ Author: your name
: SQUARE ( n -- n*n , square number )
DUP *
;
: TEST.SQUARE ( -- )
CR ." 7 squared = "
7 SQUARE . CR
;
Now save the file to disk.
The text following the \ character is treated as a comment. This would
be a REM statement in BASIC or a /*---*/ in 'C'. The text in parentheses is also
a comment.
Using INCLUDE
"INCLUDE" in Forth means to compile from a file.
You can compile this file using the INCLUDE command. If you saved your file
as WORK:SAMPLE, then compile it by entering:
INCLUDE SAMPLE.FTH
Forth will compile your file and tell you how many bytes it has added to the
dictionary. To test your word, enter:
TEST.SQUARE
Your two words, SQUARE and TEST.SQUARE are now in the Forth dictionary. We can
now do something that is very unusual in a programming language. We can "uncompile"
the code by telling Forth to FORGET it. Enter:
FORGET SQUARE
This removes SQUARE and everything that follows it, ie. TEST.SQUARE, from the
dictionary. If you now try to execute TEST.SQUARE it won't be found.
Now let's make some changes to our file and reload it. Go back into the
editor and make the following changes: (1) Change TEST.SQUARE to use 15 instead
of 7 then (2) Add this line right before the definition of SQUARE:
ANEW TASK-SAMPLE.FTH
Now Save your changes and go back to the Forth window.
You're probably wondering what the line starting with ANEW was for.
ANEW is always used at the beginning of a file. It defines a special marker word
in the dictionary before the code. The word typically has "TASK-" as a prefix
followed by the name of the file. When you ReInclude a file, ANEW will
automatically FORGET the old code starting after the ANEW statement. This allows
you to Include a file over and over again without having to manually FORGET the
first word. If the code was not forgotten, the dictionary would eventually fill
up.
If you have a big project that needs lots of files, you can have a file that
will load all the files you need. Sometimes you need some code to be loaded that
may already be loaded. The word INCLUDE? will only load code if it isn't
already in the dictionary. In this next example, I assume the file is on the
volume WORK: and called SAMPLE. If not, please substitute the actual name.
Enter:
FORGET TASK-SAMPLE.FTH
INCLUDE? SQUARE WORK:SAMPLE
INCLUDE? SQUARE WORK:SAMPLE