=== F83 TUTOR by BILL KIBLER ===
(c) 1986, 1987
== INTRODUCTION ==
F83 TUTOR is a self paced tutorial for the public domain Forth
program F83. F83 is a Forth based operating system and programing
language. This version contains the standard word set Forth-83
making the program structure different from previous standards.
Major changes between F83 and older versions of Forth (FIG AND
79) make it necessary for all users, both users new to Forth and
FIG or Forth-79 users, to study and understand these differences.
This program, TUTOR, will help new users of F83 learn to use it
more efficiently and faster.
The "CHAPTERS" are organized with the understanding that a user
will have a copy of "STARTING FORTH" by Leo Brodie. Each chapter
consists of a GLOSSARY, LIST OF TERMS, and TEXT ( in that order)
based on the books organization. Enough text is provided to get
an understanding of the topic and the book should not be required
by experienced Forth programmers. Experienced programmers will
find the GLOSSARY section to be the most important aspect of this
program. The program is based on the F83 word set and not those
of FIG or Forth-79.
TUTOR is very easy to use and can be modified to add more infor
mation or scanning functions. Experienced Forth programmers can
use this program by entering the following:
A>F83
OPEN TUTOR.BLK
1 LOAD
Use the space bar to scan through the screens of information, and
then choose a chapter to start your review. For novice or new
users of Forth a more detailed introduction follows in the next
section.
== GETTING STARTED ==
Forth is both a programming language and a operating system.
TUTOR is a simple F83 tutorial consisting of "WORDS" that handle
the information and tutorial screens based on the book "STARING
FORTH". All new or novice users should use this book, as they
will find the tutor text information to be too brief for develo
ping a good understanding of Forth. The screens of information
will help you understand Forth and will help point out the diffe
rence between F83 and the FIRST EDITION of the book. As you
follow through the screens you will notice that some glossary
words will be different from those in the book, these represent
the new word set as specified in the Forth-83 standard. Those
readers using the SECOND EDITION of "STARTING FORTH" will find
tutor to be an on disk review of the book.
To better understand this program an introduction to Forth and
its structure is needed. Forth is a stack oriented language.
Values are placed on the stack and then WORDS are entered to
perform actions on these values. The most simple use would be the
addition of two numbers. To add the numbers 4 and 7 you would
enter 4 7 + . and Forth would return 11 ok. Considerable problems
occur for new Forth users over the use of text type symbols to
represent words or commands. The sample used a . to denote the
command to print the top item of the stack on the computers
screen. In displaying information about Forth it is very hard in
a document to prevent confusion between Forth WORDS and the text
used to display them. Until you can know which words are Forth
WORDS and which are text words, reference to the text book is
needed. The book puts a block around each word when described in
the text, an option not available on all computer systems.
This problem of variations in computer systems and languages has
been handled by the FORTH INTEREST GROUP in respect to Forth. The
term FIG Forth refers to an early set of Forth WORDS that the
interest group established as the first standard Forth system.
The next standards meeting in 1979 made some changes and
established a new Forth standard called Forth-79. The latest and
one that this tutorial is intended to help is the 1983 standards
meeting version, this word set is called Forth-83. The program
this tutorial is for is F83 which is a public domain version of
Forth containing the Forth-83 word set.
Although a few words have been changed between standards a
considerable amount of similarity exists between the standards.
F83 is very popular because of its cost and utilities contained
within the program. F83 contains not only the normal screen
editor and assembler, but also debugger, disassembler, and multi-
tasker utilities. There are many commercial and public domain
versions of Forth, in fact there is a version of Forth available
for almost all the operating systems and computer hardware
systems currently being produced. Forth is a small, fast, and
extensible operating environment. It has been used in numerous
special applications, such as space vehicles, where speed and
reliability are major concerns. The extensible nature of Forth is
its most important aspect.
== LOADING TUTOR AND EXTENSIONS ==
The Forth system can be stand-alone or work within an existing
operating system. All Forths store information in SCREENS which
are 1K in size ( 1024 bytes). When a screen is displayed it can
consist of 60 characters across and 16 lines down ( one character
is equal to one byte of information). The F83 operating system
stores the screens on disk as BLOCKS of data (1 screen is 1
block). Typically the file name will have an extension of BLK to
indicate Forth information. The TUTOR program is stored as
"TUTOR.BLK" on most systems. Starting F83 would be done by typing
F83 at the system prompt and using "RETURN" on most MSDOS or CPM
systems.
To load the TUTOR program after starting F83, the file must first
be OPENED, you do this by typing "OPEN TUTOR.BLK" and a return.
Next it is necessary to LOAD the Forth extensions which are used
by the TUTOR program. You type "1 LOAD" and return, this will
start the TUTOR program and give you more information about F83.
Should your system be different or you are new to computers, you
may need to review and use programs supplied by the system manu
facturer until you understand and feel comfortable with your new
computer. Some versions of F83 use different words to open and
load files (due to operating system designs), check with your own
documentation on specific instructions.
The "1 LOAD" command loads screen 1 into memory and then starts
compiling the new word definitions contained in it. These words
are extensions to the orginal F83 word set. After being compiled
they are part of the Forth DICTIONARY and can be used as if they
were part of the original program. This ability to add words and
EXTEND the dictionary is the source of the term "extensibility".
Programs are created by extending the dictionary with new
functions and routines. The TUTORS new words are contained in 4
of the first 10 screens and can be changed should you desire some
special way of handling the tutor screens.
== TUTOR WORDS ==
The new words are:
* HELP Loads the information about the tutor program and general F83 words. The last screen lists words used by tutor and relating to "STARTING FORTH".
* START-TUTOR Will start displaying the introduction to tutorial information.
* REPT This command will display screens from the beginning of the most recent chapter or group of screens. If CHP1 had been entered and you exited the listings to try a F83 operation REPT will restarted at the first screen of CHP1.
* GET GET will start displaying screens at the next one in sequence. Using REPTs sample, if you had typed GET instead of REPT you would get displayed the next screen of information in CHP1.
* 21 TUTOR Typing this will start displaying tutor screens starting with screen 21 and continuing till the screen contains $$. When you type CHP1 this word loads the number of the first screen of chapter 1 on the stack and then goes to TUTOR.
* PRTSCR This word will display the current GET and REPT pointers.
* LIST Forths normal internal word for displaying screens of information. Use this word whenever you want to view a single screen. TUTOR uses a modified version of LIST for displaying multiple screens.
* 10 90 INDEX Use this input command line to get a list of "INDEX" lines (line 0 and NOT printed by tutor) of screens 10 through 90 (the text screens). Line 0 is generally used as a descriptive line of what the screen contains.
* ESC Using the ESCAPE key will end the display of information, so that you can then tryout some of what you just learned in the text.
== ADVANCED INFORMATION ==
TUTOR uses most of the normal F83 words to perform its functions.
A major advantage of the tutor program is to retain easy access
to the normal F83 functions. The tutor program will display a
series of screens starting with glossary information. Experienced
programmers will find this part most helpful in learning the new
F83 words. When finished displaying text screens, the F83 prompt
"ok" will indicate completion of the lesson. At this point any
F83 commands can be used. Individual screens can be repeated by
using the list function.
A number of blank screens have been provided at the end of the
program for use during the learning sessions. As new words are
created in the lesson, they can be saved in these screens and
auto loaded by adding "nn LOAD" to screen 5 (nn being first used
screen). To tie screens together use --> and F83 will continue
loading the next screen.
For educators and programmers, they will find TUTOR to be an
excellent example of how to create a tutorial program in Forth.
It is very hard to create a tutorial program in which the user
has enough control over the training structure that it can meet
their needs adequately. Most users of tutorials get frustrated
when they can not exit or reenter the program at will. Usually
lacking in tutorials is the ability to add sorting of information
or the creation of summary details. Forth appears to handle all
these problems easily. Once the user understands Forths use of
words it is possible to customize the tutorial for their personal
needs. An example of this would be the creation of a new word to
keep track of exiting and saving the screens pointers to disk.
When returning, the user would type RESTART and the disk stored
pointers would be restored, and the next screen would be loaded
for viewing.
Although not shown here, interactive uses of training are
possible. Forth has numerous words to allow for trapping of input
data and evaluating this information for correct response. The
use of screens provides a simple way of grouping information such
that a student who misses a concept (as found through testing,
see screen 39) could be directed back to that information
automatically. A new feature in F83 is the use of SHADOW screens.
These screens are from the original file UTILITY.BLK of F83 and
contain the authors comments on words in the source screens.
Words are available to toggle between these screens and the
source screens. Use of this feature may be helpful in tutorial
programs, where background or detailed discussions outside the
normal flow of instruction is needed.
== CONCLUSION ==
The creation of this program was two fold; to show Forths
abilities in creating tutorials, and to provide on disk
information about F83. This project was part of a masters program
in Computers and Education. This is by no means a complete study
of using Forth for tutorials, of F83, or Forth. I have released
this version of TUTOR.BLK into public domain solely to help those
who have had problems getting to understand the new words of F83.
One reason I feel that Forth has had problems being accepted is
the lack of tutorials accompanying new releases. When I first
tried F83, I found the on disk documentation to be inadequate.
Although the use of shadow screens is an improvement, they do not
equal the benefits of a good tutorial or disk based glossary.
I am interested in your comments concerning this program and any
information that could make it better. My time currently is
limited and thus I can only take written queries. I retain all
commercial rights to the screens 1 through 10, as they represent
the idea behind the tutorial, as well as the information con
tained within the text screens not directly attributed to
"STARTING FORTH" by Leo Brodie. I am available for commercial
activities and would be willing to assist in developing commer
cial tutorials.
Bill Kibler
Kibler Electronics
PO BOX 487
Cedarville, CA 96104
I do use the Sacramento Micro Users Group RBBS and can get
messages there: 300/1200 24 hrs (916)722-9337
ok
OPEN TUTOR.BLK ok
1 LOAD
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
*
*
PLEASE WAIT WHILE LOADING TUTOR SCREENS..TUTOR.BLK
Scr # 6 C:TUTOR.BLK
FORTH-83 TUTOR PROGRAM AND HELP SCREENS
WRITTEN BY BILL KIBLER
(c) 1987
ALL COMMERCIAL RIGHTS RESERVED
This program will help beginners and past FORTH users
alike. The screens contain information on FORTH-83 and are
related to the book " STARTING FORTH " by Leo Brodie, which
should be used as a textbook with this program. Each chapter
or series of screens is organized to present the words used in
the chapter in a glossary form. Forth users will find this
glossary important to see the differences between F83 and other
versions. Typing HELP will repeat these screens, then type
the chapter number for the area of help needed. Typing ESC key
will exit the screens and return to the system prompt. GET will
display next chapter of information, while REPT will start
with the first screen of the chapter again. START-TUTOR will
start with the introduction chapter.
NEW F83 WORDS
The following words are important utilities in F83 and may be
different from previous versions. WORDS will display a list of
F83 words used. OPEN allows use of an existing file, 10 MORE is
used to add 10 screens, and 30 CREATE-FILE NAME.BLK (opens 30
screens). INDEX displays a list of line 0, 1 20 INDEX will list
screens 1 to 20. 1 30 SHOW will print 6 screens to a page on
your printer in condensed mode ( use: ' EPSON IS INIT-PR for
epson printers). 1 30 TRIAD prints three to a page if condensed
print is not available. 1 30 SHADOW SHOW will print both the
regular screens and the information screens on a page (not used
in TUTOR but in UTILITY.BLK). SEE xxxx disassembles the word
xxxx, while VIEW will open the source file ( on A: drive) and
list the screen it is in. VOCS will list the vocabularies in
the dictionary, while ORDER displays the path of the directory
search. Use DOS WORDS to see a list of the DOS dictionary words.
CAPACITY will print the number of screens in a open file. A L
will toggle between the shadow and the source screens. N L will
display the next screen, L will list current screen, B L will
list previous screen. 1 EDIT will invoke the line editor with
screen 1 ready to edit. 0 NEW will start editing at line 0
and allow the text to be entered one line after the other. HEX
100 80 DUMP will do a hex dump of memory location 100h to 180h.
DEBUG LIST will allow stepping through list when used next as
in 1 LIST. Use BYE to exit to DOS.
TUTOR WORDS
INTRO = introduction CHP1 = fundamentals
CHP2 = RPN and STACK CHP3 = editor commands
CHP4 = conditionals, nests CHP5 = fixed point operations
CHP6 = loops ( & nested) CHP7 = number types
CHP8 = var. const. arrays CHP9 = F83 structure
CHP10= Input/Output CHP11= extensions
GET = next chapter REPT = begin chapter again
HELP = repeat these screens START-TUTOR = start at INTRO
SPACE BAR = next screen ESC = stops display
BYE = EXITS to DOS MENU = displays this screen
PRTSCR = GET and REPT pointers
$$
ok
GET
Scr # 10 C:TUTOR.BLK
INTODUCTION
Forth is a stack oriented language, a hardware independent
programming language and operating system. F-83 is based on the
Forth-83 Standard with enhancements to make it a full operating
environment.
F-83 contains the Forth-83 word set, plus words for
debugging, editing, disassembly, assembly, DOS functions and a
multitasking system.
The F-83 system is available on all standard computers
currently being manufactured; providing a complete set of
portable system utilities that are independent of hardware.
Use this tutor program to learn F-83 and the differences
between this version and past or commercial versions of Forth.
HELP will display a summary of information about F-83 and this
tutor program.
This tutorial uses the well known and popular text "STARING
FORTH" by Leo Brodie. Many references are made to the text and
it should be used to obtain detailed information about Forth.
The program does not cover everything about F83, but only
attempts to provide on line help information and instruction.
There are two versions of "STARTING FORTH" currently being
used. The first edition did not contain any reference to F83
and was printed before 1982. This tutorial will help people with
the first edition see the differences between FIG, Forth-79
and the new F83 (Forth-83).
The second edition is mostly the same information with
changes for the newer Forth-83. Some minor text changes have
been added to improve the understanding of some terms. All the
other changes are related to the new or different commands used
by F83 or contained in the Forth-83 standard. $$
ok
GET
Scr # 12 C:TUTOR.BLK
GLOSSARY OF CHAPTER 1
: xxx yyy ; ( - ) Creates word xxx which does word yyy
CR ( -- ) Do a carriage return and line feed
SPACES (n -- ) Print n number of spaces
SPACE ( -- ) Print one blank space
EMIT (c -- ) Transmit a character to output device
." zzz" ( -- ) Print the output string zzz at terminal
+ (n1 n2 -- sum) Adds n1 to n2 and leaves sum on stack
. (n -- ) Print number on top of stack followed by space
( xxx) ( - ) Comment, ignored by the text interpreter
TERMS IN CHAPTER 1
COMPILE To generate a dictionary word
DICTIONARY Forths list of words or operations
EXECUTE To do the operations a word stands for
EXTENSIBILITY Ability to modify, add or change words
GLOSSARY A list of words defined and explaned in Forth terms
INFIX NOTATION Using operators between operands
INPUT STREAM Text to be read by TEXT interpreter
INTERPRET To compare input text to FORTH words
LIFO Last In First Out..how the stack works
POSTFIX OPERATION The way FORTH operates..RPN
STACK A section of memory used as a data stack
STACK OVERFLOW Stack operations used all allocated stack
STACK UNDERFLOW Operations tried to read data from empty stack
WORD The name of a FORTH definition
CHAPTER 1 FUNDAMENTAL FORTH
FORTH has two main features, EXTENSIBILITY and INTERACTION.
New functions are added to the language by creating new words
and adding them to the dictionary of existing words. This
operation is called extending the dictionary, and thus the term
"extensibility". As each new word is created it can be used
immeadiately to see if it functions properly. This instant
adding and execution of the word is the reason behind the term
"interactive".
When Forth is waiting for your input, your terminal will
have displayed "ok" on the previous line. This means the
interpreter is waiting for your next input. That input can
be a direct command such as 42 EMIT which will output the
ASCII character * (star) to your terminal.
To make a new word for the dictionary, you need to follow
the definition structure, this is a colon (:), a space, the
name of your word (star), a space, the definitions, a space,
and lastly a semicolon indicating the end of the word. Follow
the semicolon (;) with the return key and the action you have
defined will take place.
FORTH is stack oriented, the input string is processed
and input which is not a defined word, is assumed to be a
numeric input and is pushed onto the stack. Numbers are pushed
until a word is found, where upon the functions defined will be
performed on the numbers on the stack from the top down.
In the line 2 4 + . we have the numbers 2 and 4, a plus sign
to add the two number on the stack, and a period which prints
the top value on the stack. This means 2 is pushed first, then
4 is on top, the + sign is interpreted and Forth adds the 2 and
4 getting 6, and places six on the stack. The next command, the
. removes the 6 from the stack and converts it to the ASCII
equivalent, before outputting it to the screen. The screen can
not print numbers directly, but there is a standard number which
is used to represent the number 6, this is ASCII number 54.
To display the manner in which your word handles the stack
a standardized convention is used. The ( n1 n2 -- sum ) is
used to indicate that the first number ( n1 ) is push on the
stack first, followed by n2, the second number. Forth then
( -- ) reads the word and performs the function, placing the
results ( sum ) on the stack. The right most item is the one
currently on top of the stack, or you read from left to right
which corresponds to bottom of stack to the top.
This has been a brief summary of fundamental forth as was
presented in "Starting Forth", please study it for more details.
You can now try some of the samples listed in the book, just
wait for the "ok" prompt after you hit the space bar again. Try
inputting the line displayed below, to define the new word GREET
: GREET CR ." HELLO, I SPEAK FORTH " ;
Create a word that asks for your name.
Scr # 18 C:TUTOR.BLK
GLOSSARY OF CHAPTER 2
+ (n1 n2 -- sum ) adds two stack items, leave sum on top
- (n1 n2 -- diff) subtract n2 from n1, results on top
* (n1 n2 -- prod) multiplies n1 times n2
/ (n1 n2 -- quot) divides n1 by n2, quotient on top
/MOD (n1 n2 -- u-rem u-quot)
divides and leaves quot on top, remainder below it
MOD (n1 n2 -- u-rem) divides and leaves only the remainder
SWAP (n1 n2 -- n2 n1) swap the order of the top two items
DUP (n -- n n) make the top two items the same
OVER (n1 n2 -- n1 n2 n1) copy second item on top of stack
ROT (n1 n2 n3 -- n2 n3 n1) puts third item on top of stack
DROP (n -- ) throw away top stack item
2SWAP (d1 d2 -- d2 d1) swap the top two PAIRS of numbers
2DUP (d -- d d) duplicates the top PAIRS of numbers
2OVER (d1 d2 -- d1 d2 d1) copy second PAIR, push on top
2DROP (d -- ) drop the top PAIR of number off of stack
TERMS IN CHAPTER 2
DOUBLE LENGTH NUMBERS Twice the length of the hardwares normal
word length. In 16 bit words that would be a 32 bit number
and typically is a value of plus or minus 2 Billion
SINGLE LENGTH NUMBERS The normal length of words used by this
version of Forth, typically -32768 to +32767. These are
intergers or whole numbers (no decimal points allowed)
Chapter 2 How to get results
Forth arithmetic is similar to a number of calculators one
can buy. These calculator are usually called RPN or Reverse
Pollish Notation calculators. They operate on a stack type
structure and require at least two items on the stack before
you can add, subract, multiply, or divide. Forth uses the +
(plus) sign for addition, - (minus) sign for subtraction, *
(star) for multiplication, and / (slash) for division.
These procedures are used with interger math, or whole
numbers only. On most Forths these are +32767 to -32768. This
interger math requires some thought on the users view point.
Numbers larger than these require other words or double length
operators, which are covered in chapter 7. For now lets look at
using whole numbers in division.
Interger math requires more than one step when dividing. What
happens is the results and the remainder are treated as two
separate whole numbers. The operation 20 4 / will divide 4 into
20 and produce the whole results 5. 22 4 / will also produce
the same answer 5, the remainder 2 is lost. If we use 22 4 MOD
we get remainder only 2. To get both the results and remainder
you can use /MOD as in 22 4 /MOD puts 5 on top of the stack
the remainder below it. Remeber the . will print the top stack
item and make the second item the top element.
In most math operations there is a means of specifing the
order of operations. With forth being stack oriented order is
determined by placement in the stack. A infix presentation of
4+(17*12) would be presented in forth as 17 12 * 4 + . with
208 being displayed. Numbers are pushed onto the stack while
the operators are performed in a left to right manner. We see
that 4 17 12 * + is the same as the previous problem. The * is
performed first on the top items (17 and 12) then the + is
used on the top (204) element and the second, now 4. The . will
print the results of 208.
There are several ways of handling the stack order and making
changes to it. If you want the results of a math operation to be
printed but still available for the next operation, you DUP
the results before printing it. DUP takes and pushes the top
item on the stack down one and makes a copy of it on the top of
the stack. OVER will make a copy of the second item and place it
on the top, or DUP the second item. To reverse the top two items
on the stack you would use SWAP. To get the third item on top
and make items 1 and 2 now 2 and 3 respectiviely you use ROT. If
you want to remove the top item we just DROP it off the stack.
Later on we will deal with double length number (larger than
32768), we also have double word or item operators, these are
2SWAP, 2DUP, 2OVER, 2DROP. These perform the same operation as
their single counterparts, they just work on two stack items at
a time. 2DROP will DROP the first and second items off the
stack.
For more samples of these operations check the book, or play
around with forth when you see the ok after this screen. Here
are some sample problems:
if a=4 and b=8 what is a*(a+b) there are two ways to do this
if c=3 then evaluate ab - bc again two ways here too
make a new word that will return the number of kilometers when
the top stack item is number of miles.
Try these problems or make up some of your own...
In this screen...number 24
Scr # 25 C:TUTOR.BLK
CHAPTER 3 GLOSSARY ( EDITOR )
LIST (n -) Display screen n and make it current screen
LOAD (n -) Load n screen and interpret into dictionary
FLUSH SAVE-BUFFERS and de-allocate buffers in memory
SAVE-BUFFERS Write all buffers to disk files ( also use W )
UPDATE Mark current screen for save to disk
L Display current screen
N L Display Next screen
B L Display previous (Back one) screen
A L Toggle between current and shadow screens
T (n -) Make n the current line to edit
P xxxx Put the string xxx in the current line
U xxxx Insert the string xxxx under the current line
K ( -) Exchanges the contents of insert and find buffers
X Delete current line
NEW (n -) Input multiple lines starting at n
F xxxx Find and move to END of xxxx
D xxxx Delete string xxxx and leave cursor at string
TILL xxxx Delete all text from cursor to end of xxxx
J xxxx Delete till begining of string xxxx
EDIT (n -) Invokes editor on n screen
EDITOR Makes the editor vocabulary current vocabulary
DONE Do flush and return from editor vocabulary
ED Return to editing current screen
FIX xxxx Find xxxx in unknown screen and start editing it
OPEN xxxx Open file xxxx.xxx and make it current file
MORE (n -) Add n more screens to the end of current file
COPY Copy screens from one file to another
CONVEY Move screens around within file
FORGET name Removes all word definitions back to name
THRU (lo hi -) Loads all blocks between lo and hi inclusive
TRIAD (n -) Print three blocks around n on a page
SHOW (lo hi -) Print 6 blocks to a page in condensed mode
VIEW name Find name in source screen and list it
WIPE ( -) Blanks the entire screen when editing
G ( blk ln -) Gets copy of line from block and insert above
current line pushing lines down
BRING ( blk lo hi -) GETS range of lines
S xxx (n - n) Searches for xxx in blocks n up if found n on top
LISTING name Print entire open file including shadows
KT xxx Put all text between cursor and xxx in insert buffer
O xxx Overwrites xxx onto text of current line
SPLIT Breaks current line in two at the cursor
JOIN Puts a copy of next line after the cursor
QUIT Exit editor WITHOUT updating buffers to disk
CHAPTER 3 TERMS ( EDITOR )
BLOCK The means of which files are divided, 1024 characters
is one block (BLK) and is used as screens (SCR) in forth
BUFFER Temporary space set aside in memory to hold BLKs or SCRs
DISK A short term for floppy disk and data stored there
EDITOR The forth vocabulary that contains words used by editor
FIND BUFFER The buffer containing the find string
INSERT BUFFER The buffer containing the insert string
LOAD BLOCK The block which loads other blocks or screens
NULL DEFINITION A word that has no action, a marker
OVERLAY Data that will replace previous data or words
POINTER A value or location that points to other data
SOURCE TEXT The text which is the original definition of a word
CHAPTER 3 THE EDITOR
Forth contains a built in line or screen editor. This editor
is not like some commercial word processors, but more like the
line editors which come with most operating systems. Forth
stores all the source code for itself as plain text in screens.
The plain text statements are compiled through a special META
compiler to produce the F83 machine code program. Two files
contain most of the source code for F83, they are UTILITY.BLK
and KERNELxx.BLK. UTILITY contains the higher level utility
functions which you use, such as the editor's source code. The
KERNELxx contains all the screens necessary for making the main
F83 kernel as would be used on xx processor. The xx stands
for 86, a short way of saying 8088/86 CPU which is used in the
IBM PC line of computers.
Suppose you want to change some printer directives, which
are in the utility files. Currently F83 uses Epson printer codes
when invoking condensed modes of printing. Your printer uses
different codes from the Epson. To find the screen where this
code is we use FIX EPSON, after the file has been opened using
OPEN UTILITY.BLK. This will display the screen (44) which has
the source code word EPSON, and position the editor after this
word. You can now use the editor commands to change the control
code invoked using the word EPSON. When you have made the change
DONE will exit the editor saving changes. Reloading the sytem
will give you the new printer commands. Also you could have
entered the minor changes directly from the terminal, but you
would have to do this each time you loaded the system.
In creating this tutor program, I have created a number of
blank blocks by typing 30 CREATE-FILE TUTOR.BLK. This then
allows me to do 1 EDIT and start creating the source code for
this program. The editor will then ask me for the ID........
and I will type my initials and current date. Becuse not all
forths reconize the back slash as comment line I use the ) as my
last item in the ID line. I start my screen with 0 NEW and will
type the first entry starting with a ( indicating a comment
is next. At this point you can type text one line after the
other, watching for the end of the line, the editor does not. 2
blank lines denotes end of NEW lines and you can then go back
and correct any mistakes.
Some samples of editing are; 3 T to select line 3 to edit.
Using P NOW will put NOW on line 3. U NEXT will put NEXT on line
4. If we type F T the cursor will be after the T on line 4. Now
you can type I TIME and line 4 will have NEXTTIME on it. To get
space between the Ts go 4 T again to get back to the begining of
the line, then F again (no T needed, buffer still has it) and
the cursor will be after the first T, do I with two spaces, the
return will then put a space between the Ts. You can of course
start a line with spaces or any items. The editor is not very
fancy, but it is in most versions of forth, meaning once learned
you can use it on any machine your forth is running on.
The instructions in the text are similar and do cover the
main commands used in most forth editors. F83 uses different
commands to move screens around. To load screens from the
utility file to this (which is already open and is the current
file) you would type FROM UTILITY.BLK 1 10 COPY this will copy
screen 1 of utility to screen 10 of TUTOR. Now to copy a string
of files you use CONVEY, such as 11 HOP 1 6 CONVEY to copy
screens 1 to 6 of TUTOR to 12 to 17 of TUTOR. The HOP means to
jump over 11 screen from the first one and start the copying
there. 1 6 TO 12 CONVEY does the same as 11 HOP. For moving
screens between files, we would use the FROM UTILITY.BLK command
(after the OPEN TUTOR.BLK) and then 1 20 TO 30 CONVEY and this
will copy screens 1 to 20 of utility to 30 to 50 of tutor. You
may need to do 20 MORE first, which adds 20 empty screens to the
currently opened file.
If you have made backups of the TUTOR.BLK files, now would
be a good time to try editing. If you use 25 35 INDEX you will
find out which screens are blanks and you could use one of them.
The last screens are blank and ready for your playing around.
Try creating some new words and then LOAD the screen, which will
add the words to the dictionary. Another way to find empty
screens is 1 IND this will give the index or line 0 of each
screen starting with 1 until end of file is reached or you hit
the ESC key. Use QUIT if you dont want to save edits........ $$
Scr # 34 C:TUTOR.BLK
CHAPTER 4 GLOSSARY ( DECISIONS )
IF xxx IF: (f -) If f is true execute xxx, otherwise do yyy
ELSE yyy continue with zzz regardless, the ELSE yyy
THEN zzz is optional.
= (n1 n2 - f) Return a true flag if n1 and n2 are equal
<> (n1 n2 - dif) Returns true if n1 and n2 are not equal
< (n1 n2 - f) Returns true if n1 is less than n2
> (n1 n2 - f) Returns true if n1 is greater than n2
0= (n - f) Returns true if n equals zero
0< (n - f) Returns true if n is negative
0> (n - f) Returns true if n is positive
NOT (f - f) Reverse the results of the last test (0=)
AND (n1 n2 - and) Returns the logical AND of n1 and n2
OR (n1 n2 - or) Returns the logical OR of n1 and n2
?DUP (n - nn) or (0 -0) Duplicate only if n is nonzero
ABORT" xxx " Abort operation and print xxx error message
(f -) also clear users stacks, if false no action
XOR (n1 n2 -xor) Exclusive or, true if both n not true
CHAPTER 4 TERMS ( DECISIONS )
ABORT Abruptly cease operation if procedure isn't acceptable
AND Output is true if both inputs are true
BRANCHING If input condition occurs jump to another routine
COMPARISON Check and flag if two items are the same
CONDITIONAL Different operation if flag true than when false
FLAG A variable when set equals true, reset equals false
LOGIC Using operators like AND, OR, NOT to make statements
NESTING Branching routines within branching routines
OR If either of two inputs are true the results is true
CHAPTER 4 DECISIONS, CONDITIONALS
In any computer language, terms are used to express math
forms and types. We like to compare items and say how one is
larger or smaller than an other. You may also base an action
on the results of such a comparison. Forth can also do the
same types of comparisons. We can tell forth to do something IF
some condition is met. The proper term for this is IF THEN
statements. To help make these comparisons there are several
operators we can use. They can be = for equals, < 2nd stack item
is less than top item, > 2nd item is greater than top item, 0=
the top item is equal to zero, 0< the top is less than zero, 0>
the top is greater than zero.
All of these operations depend on setting a FLAG variable.
This flag is a special indicator set as either true or false.
IF THEN logic operations work by checking the flag to see if it
is true or false. If true THEN do xxx ELSE if false do zzz.
The IF statement can be any form of testing, including regular
math operations. A sample math operation is comparison <> where
if two items are the same, the results will be zero, and so the
flag will be set false (treated as subtraction).
There are non math operators that can do comparison based on
logic operations. These logic operators are AND, OR, and NOT.
AND sets the true flag if both stack items are also true, OR if
either stack items is true, while NOT reverses the flag setting.
Forth has some words which contain conditional tests within them
ABORT" and ?STACK. ABORT" print the statement contained within
the " " if the flag is set, leaves the current program and
resets all stacks before the Forth ok. ?STACK flags true if
the stack is empty, as when waiting for keyboard input.
Lets do a simple IF THEN routine to show the forth way of
handling conditionals. Lets test to see if a pupil answers a
question correctly when faced with four choices;
: ckansw ( check the answer and prompt accordingly )
DUP 1 = IF ." WRONG" CR 12 TUTOR ELSE
DUP 2 = IF ." CLOSE BUT REREAD QUESTION " ELSE
DUP 3 = IF ." GOOD CHOICE " ELSE
DUP 4 = IF ." BETTER LUCK NEXT TIME.. " ELSE
." ENTER VALUE OF 1 2 3 or 4 ONLY "
THEN THEN THEN THEN DROP ;
This new word CKANSW, checks the item on top of the stack to see
if it matches or equals the value we want. If it does, print the
statement and then continue checking unitl last "then" is used.
When a non match occurs the prompt to enter a new value is now
displayed. Try your own conditional program in SCR # 39.....
( here it is for you to change or use )
: ckansw ( check the answer and promt accordingly )
DUP 1 = IF ." WRONG" CR 12 TUTOR ELSE
DUP 2 = IF ." CLOSE BUT REREAD QUESTION " ELSE
DUP 3 = IF ." GOOD CHOICE " ELSE
DUP 4 = IF ." BETTER LUCK NEXT TIME.. " ELSE
." ENTER VALUE OF 1 2 3 or 4 ONLY "
THEN THEN THEN THEN DROP ;
Scr # 40 C:TUTOR.BLK
CHAPTER 5 GLOSSARY ( INTERGER MATH )
1+ (n - n+1) Adds one to n
1- (n - n-1) Subtracts one from n
2+ (n - n+2) Adds two to n
2- (n - n-2) Subtracts two from n
2* (n - n*2) Multiplies n by two (shift left )
2/ (n - n/2) Divides n by two ( shift right )
ABS (n - |n|) Returns absolute value of n
NEGATE (n - -n) Changes the sign of n
MIN (n1 n2 - n-min) Returns the minimum n (either n1 or n2)
MAX (n1 n2 - n-max) Returns the maximum n (either n1 or n2)
>R (n - ) Place stack top item on return stack top
R> ( - n) Load top of stack with top of return stack
R@ ( - n) Make a copy of return stack, put on top of stack
*/ (n1 n2 n3 - n) Multiplies then divides (n1*n2/n3)
*/MOD (n1 n2 n3 - n-rem n-result) Get remainder, quotient on top
CHAPTER 5 TERMS ( INTERGER MATH )
Double length intermediate result Steps within an operation in
which the number size has twice the normal digits, inorder
to minimize errors.
Fractional arithmetic The handling of numbers without the
decimal point, using whole numbers, and later returning
the decimal point to its proper place. FIXED POINT can be
used inplace of fractional, they mean the same.
Floating point math Number containing the decimal point
and requiring adjustments before use by a computer.
Parameter stack The main data stack which is used to pass
data between operations of the forth machine. Generally
referred to simply as STACK or data stack.
Return stack The stack used by forth for keeping return
addresses on during operations. Can be used for holding
data from stack (parameter) only WITHIN a definition.
Always referred to as RETURN STACK, never stack!
Scaling The adjustment of floating-point numbers such that
all number are represent as intergers and with the same
relevant relationship in respect to the decimal point.
CHAPTER 5 INTERGER MATH
Forth has a number of words that help perform math operations
quickly and easily. All of these operations work on INTERGER
MATH concepts, or interger numbers. Typically these are signed
numbers between +32768 and -32767. To add numbers that have a
decimal point we mentally multiply the number by a power of ten
enter those numbers and then replace the decimal point after the
operation. Some versions of Forth contain routines that will do
this for you, they are called floating point utilities. They can
slow down Forth considerably and waste memory.
Most Forth users prefer to use interger math for the speed
and memory savings. There are two words that help make interger
math easier */ (star slash) and */MOD (star slash MOD).
These words perform a multiply and then a divide (MOD produces
a remainder). Scaling is the method used in forth to change a
value so that it can be used in interger math. To use numbers
we scale them before use, then rescale the results back into the
same ratio. We can use PI not as 3.1416 but 31416 10000 / and
when used in a formula like PI * Dia for area we use */ as in
4 31416 10000 */ . and we get the area of a 4 foot circle. We
have made the results of 4 * 31416 be 10000 time larger than in
you would using PI as 3.1416, but by dividing our results by
10000 we return it to proper scale. PI however has more places
than four shown and will produce some error. There are fractions
which can represent a more accurate means of expressing this and
other numbers, they are called rational approximations, here are
a few: PI 355/ 113, SQRT of 2 19601/13860, SQRT of 3 18817/
10864, .001Deg./22-bit rev. 18118/21109.
To find our answer to the area of a 4 foot circle use the
values of PI: 4 355 113 */ . this will be more accurate than
before. */ does not produce a remainder and the area of the last
problem is more than 12 square feet. Using */MOD will provide
the remainder as the second item on the stack. When using the
remainder we can then see the difference between dividing by
10000 and using 355/113, which is .0736. For a more detailed and
illustrated review of this topic check chapter 5 in STARTING
FORTH.
The return stack is used by Forth to store return addresses
of definitions (semicolons). It can be used within a definition
to help shuffle values around. A good example of that would be a
problem that uses a constant several times. Instead of dupping
the number and a ROT or SWAP it may be faster to copy it to the
return stack and make copies of it each time you need it. You
must remember to clear the return stack by the end or ; .
To help moving between the return stack and parameter stack
use >R to push on R< to get off and back onto the stack. R@
makes a copy of top of return stack and places it on top of
data stack.
In most programs there are several operations that occur
frequently and Forth has words to help out with them. Many a
time we need to add or subtract by 1 or 2, and thus the words
1+ 1- 2+ 2- 2* 2/ . Filtering of values is also important, so we
have ABS for absolute value, NEGATE for changing signs, MIN and
MAX to find the relationship between 2 values.
Try these problems or write a new word in screen 47 for each
of these inputs,0 degrees F and 45 degrees C. Use these formulas
C= (f-32)/1.8 and F= (C*1.8)+32 . Try and find the radius of
a circle with a circumferance of 23 feet.
What is the area of circle 12.5 feet in diameter?
Scr # 48 C:TUTOR.BLK
GLOSSARY CHAPTER 6 ( LOOPS )
DO ... LOOP DO: (limit start -- ) LOOP: ( -- ) This word
sets up a finite loop, with a starting value and
a ending or limit value ( loop does no action
accept return to begining of DO).
DO ... +LOOP DO: (limit start -- ) +LOOP: (n -- ) Same as
plain loop, but adds n to value each time it loops.
LEAVE ( - ) Terminates loop at next LOOP or +LOOP.
BEGIN .. UNTIL UNTIL: (f - ) Loops until f becomes true.
BEGIN xxx WHILE yyy REPEAT WHILE: (f - ) Loop doing xxx
while yyy remainds true, leave when f is false.
.R (n width -- ) Prints unsigned value right justified
within specified field width.
PAGE ( - ) Send a form feed to the terminal or printer
QUIT ( - ) Kills current execution and returns to terminal.
CHAPTER 6 TERMS ( LOOPS )
DEFINITE LOOP A looping routine which will execute as many
times as needed to reach a fixed value after starting
from some preset value.
INFINITE LOOP More often called a LOCKED UP COMPUTER, one that
will never reach a determined value.
INDEFINITE LOOP Not to be confused with a infinite loop, this
loop ends when some predetermined value is reached.
Changes in flags or values will end these loops. This
loop starts with BEGIN, while definite loops use DO.
CHAPTER 6 LOOPS
Loops are an extension of branching, it's just that they will
branch back to the begining of the word DO or BEGIN. A DO loop
takes values off the stack, the starting value on top and the
ending value below. The staring value is increased by one each
time through the loop until it equals the ending value. The
operations contained within the DO and LOOP are performed until
the items are equal. These items are not kept on the data stack
but stored on the return stack, which you can copy and print by
using the word I (see last chapter for more info). This value
is called the index and can be used within the loop to create
new values or pointers.
+LOOP takes the value off the stack and increments the loop
counter by this amount. +LOOPs can then count by steps to the
limit value, which is the second value on the return stack (use
I' to copy to data stack). Be careful of using 0 in loops,
becuse you could end up multiplying by 0 and never reach your
ending value, this is an infinite loops, never ends.
The other form of looping is the indefinite loop which
starts with BEGIN and ends with UNTIL. This loop will repeat
what is between the BEGIN and UNTIL, as long as the flag remains
true. This means you must perform some test within the loop
that will change the flag. A modified version of this loop is
BEGIN WHILE REPEAT loop. This loop works just the opposite of
the BEGIN UNTIL loop, it works only while the flag is true.
When the flag goes false this loop ends.
A regular DO LOOP can be ended early by LEAVEing it. Using
LEAVE within the loop will terminate the loop, so to prevent an
unwanted leave, enclose the term LEAVE within an IF THEN
statement. The IF is checked and as long as the condition is not
true, the loop will not be terminated by LEAVE but continue on
with THEN.
The text has several good examples of DO LOOPs and how to
use them. The text omits any BEGIN UNTIL loop problems, so lets
see if we can create a word using this loop. If printing stars
on the screen remember to clear it first with PAGE. Now lets
see if you can create a christmas tree using stars when the
stack contains the height or width as a value.
Should you want to see a sample of printing a tree with
the lowest branch value used as width, displayed at begining,
then enter 25 TREE for a tree with 25 stars accross the bottom.
If you want you can try and make the value enterd equal the
number of branches ( not stars ) by editing screen 53. Try it
first before looking at screen 53, it is more fun..... $$
ok
GET
Scr # 53 C:TUTOR.BLK
: STAR 42 EMIT ; ( print star )
: STARS 0 DO STAR LOOP ; ( print many stars )
: TREE ( n -- ) ( expects width to be on top of stack )
2/ 2* 1 + ( guarantee it is odd )
PAGE CR CR ( clear screen and move down )
1 39 DUP SPACES STAR ( get set and do a star )
BEGIN CR 1 - DUP SPACES ( start and move across )
SWAP 2 + DUP STARS ( set star count do it )
ROT SWAP >R DUP R> SWAP >R DUP >R ROT
R> R> = UNTIL ( shuffle and check star to count )
CR 39 SPACES STAR CR 39 SPACES STAR CR CR ;
( the last line draws the tree stock and moves ok down )
( $$ )
ok
GET
Scr # 54 C:TUTOR.BLK
CHAPTER 7 GLOSSARY ( NUMBERS )
ASCII ( - c) Translate character into ASCII equivalent
U. (u - ) Prints unsigned number and one space
U.R (u wdth -) Display right justified unsigned number
U< (u1 u2 - f) Flag true if u1 < u2, single length unsigned
HEX ( - ) Set number base to sixteen
OCTAL ( - ) Set number base to eight ( not on all systems )
DECIMAL ( - ) Set number base to ten
<# Begins number conversion, unsigned double length
# Converts digit to output character string
#S Convert number until result is zero
c HOLD Insert an ASCII character in string at HOLD point
n SIGN Inserts minus if n is negative in string
#> Leaves number string and stack ready for TYPE
D+ (d1 d2 - d-sum) Adds two 32 bit numbers
D- (d1 d2 - d-diff) Subtract two 32 bit numbers
DNEGATE (d - -d) Change sign of 32 bit number
DABS (d - |d|) Returns absolute 32 bit value
DMAX (d1 d2 - dmax) Returns maximum of two 32 bit numbers
DMIN (d1 d2 - dmin) Returns minimum of two 32 bit numbers
D= (d1 d2 - f) Flags true if d1 and d2 are equal
D0= (d - f) Flag true if d equal zero
D< (d1 d2 - f) Flag true if d1 less than d2
DU< (ud1 ud2 - f) Flag true if unsigned d1 < unsigned d2
D. ( d - ) Prints signed 32 bit number
D.R ( d width - ) Prints signed 32 bit right justified
UM* (u1 u2 - ud) Multiply two 16 bit, gets 32 bit unsigned
UM/MOD (ud u1-u2 u3) Divides 32b by 16b, gets 16b rem and quot.
M* (n1 n2 -d-prod) Multiplies two 16b gets 32 bit result
M+ (d n - d-sum) Adds a 32b to 16b, returns 32bit number
M/ (d n - n-quot) Divides 32b by 16b, get 16b signed results
M*/ (d n u - d ) Multiplies then divides 32 by 16 get 32 bit
CHAPTER 7 TERMS ( NUMBERS )
ARITHMETIC SHIFTS Process of moving bit left or right, which
is same as multiplying or dividing by two.
ASCII The standard system of representing characters with
numbers, eight bits in length.
BINARY Number base of two, either on or off
BYTE Term for 8 bit value
CELL A Forth term for 16 bit value
DECIMAL The number base of 10
HEXADECIMAL Number base of 16
LITERAL A number that appears inside a definition
MASK A means of filtering out unwanted bits
NUMBER FORMATTING Changing binary number to display characters
OCTAL Number base of 8
SIGN BIT A bit used to indicate sign in signed numbers
TWO'S COMPLIMENT The binary method used to add negative values
UNSIGNED NUMBER A positive number
UNSIGNED SINGLE LENGTH NUMBER An interger between 0 and 65535
WORD In Forth the defined dictionary entry that will
perform some function or command
CHAPTER 7 NUMBERS
Computers have only one way to handle numbers, that is the
BINARY method. Everything inside computers is either a one or
zero, a on or off, or combinations of these two states. Binary
is the term for this type of handling data. Humans however have
considerable trouble understanding these on and offs values, so
we have created number systems for the different ways we want to
represent data.
In a previous screen I indicated that ASCII characters is
what a computer uses to display information. A number has been
asigned for each character we wish to display. These and any
number can be represented in a binary form. To send a carriage
return to your screen we send a value of 13 decimal. The binary
representation of 13 is 00001101 and is what the computer
actually sent to the display. Several shorthand methods are used
to indicate binary values. Some older computers use OCTAL or
base 8. Most new machines use HEXADECIMAL or base 16. Four bits
of binary 1 or 0s is used to get the hexadecimal value. Four HEX
(short for hexadeciaml) values will represent the sixteen bits
used in most of Forths single numbers. Double numbers are based
on using 32 bits or eight hex values. Remember the hex values
are just easy ways to express the 4 places of on and off data.
In forth we use normally 16 bits to represent an unsigned
number, 15 bits for a signed number with the 16th bit being the
sign. When counting in binary that is 65535 for unsigned and a
range of +32768 to - 32767 for signed numbers, all 16 bits. For
binary arithmetic check the book, it has some good samples
There are a number of Forth words which binary understanding
helps in knowing what they do. ASCII numbers are used by the
EMIT word. This command emits an number to the display system.
F83 can take a character and automatically convert it to a ASCII
value. Using ASCII * EMIT will send a star to the display. The
same technique is used when changing base number systems. HEX
0A 12 + . will produce 1C as the answer. To get a decimal value
do HEX 0A 12 + DECIMAL . and it will print 28.
There are many ways to display numbers in Forth. To print
unsigned (16bit) numbers U. will print what is on the stack plus
a space after it. If you want numbers in a column use U.R where
stack top has the width of the column, and the second down has
the number that will be right justified. For DO LOOP compares on
unsigned numbers use U< to flag true if U1 is less than U2. We
can do the same functions with double length numbers (32bits).
D. prints signed numbers, UD. prints unsigned numbers, D.R like
U.R for signed 32 bit numbers, and DU< is 32 bit U<.
To display numbers it is necessary to format their output.
This formatting inserts . or / to indicate money or dates. The
method in Forth is to asign positions in a string, relative to
digits in the number being printed. The format words are <# # #>
and HOLD TYPE #S ASCII all can be used within the string. To
start a layout use <# then number of numbers used, your period
as a number (45) HOLD to hold a place by inserting a . there
and then #S to fill in any remainding numbers. The real problem
is the left most #, will be the right most number, or if we have
4 #s before the hold, it will have four values after the HOLD.
We also need to end the string with a #>, followed by TYPE which
will display the formatted number. No space is printed after
TYPE so you may need to follow it with a SPACE or n SPACES. You
should try some of the samples in the book to get a better
grasp of number formatting.
There are a few double length operators that help handle
relationship between numbers. These are, DNEGATE which changes
the sign of a 32 bit number, DABS that returns the absolute
value, DMAX and DMIN for minimum and maximum of two numbers, D=
set flag true if two doublelength numbers ar equal, D0= if the
number is zero, D< true if d1 is less than d2. Remember these
operate the same as their single length number, but work on 32
bits of data, not 16.
As with single length number, some operations will require
intermediate answers that are longer than 32 bits. In */ the
16 bit values used a 32 bit intermediate value to maintain the
accuracy. M*/ takes a 32 bit number and multiplies it by a 16
bit getting a triple length results (48 bits), and then dividing
by a 16 bit number, return the answer as a 32 bit value.
There are several other MIXED LENGTH OPERATORS, they are UM*
mulitplies two 16 bits for a 32 bit answer, UM/MOD divides a 32
bit by a 16 bit, getting 16 bit answers all unsigned, M* takes
two 16 bits and multiplies for a signed 32 bit value, M+ adds a
32 and a 16 bit number for a 32 bit answer, M/ a 32 by 16 for a
16 bit answer.
One must remember that the number base you are in is used when
compiling a word. Inserting a HEX will not have the values in
the word compiled as hex values if you are in decimal at the
time. When words are executed, if they contain a number base,
the base will change at that time and interpret the numbers that
were stored literally into the equivalent base value.
The book has more details and some interesting problems. A
good problem is creating a BIT mask using a DO LOOP. A good and
useful word would be one that display bit patterns for values
entered, in both 16 and 32 bit lengths.
Try some large size math problems using the new words from
this chapter.
Scr # 66 C:TUTOR.BLK
CHAPTER 8 GLOSSARY ( VARIABLES )
CONSTANT xxx ( n -) Creates a constant xxx with a value of n
VARIABLE xxx ( - ) Creates a variable xxx, xxx gets address
CREATE xxx ( - ) Creates dictionary header xxx
! ( n a -) Stores single length number into address
@ ( a - n) Fetches contents of address to stack
? ( a - ) Prints contents of address and a space
+! (n a - ) Adds n to contents of address (single length)
ALLOT ( n - ) Adds n bytes to the PFA of recently defined word
, ( n - ) Compiles n into next available cell in dict.
C, ( b - ) Compiles b ( byte) into available cell of dict.
C! (b a - ) Store a 8 bit value into address
C@ ( a - b) Fetch an 8 bit value ( byte) from address
FILL (a u b -) Fill memory u bytes long, starting a, with b
ERASE (a u -) Stores u zeros starting at address a
BASE ( - a) Variable containing value of number base
DUMP (a u - ) Display u bytes of memory from a address
2VARIABLE xxx Creates double length variable
@CONSTANT xxx Creates double length constant
2! ( d a - ) Stores double length number into a address
2@ ( a - d ) Fetches double length double from a address
0. ( - 0 0 ) Puts a double length zero on stack
FALSE ( - 0 ) Returns a zero or false condition
TRUE ( - -1) Returns a -1 or all 16 bits set to one
CHAPTER 8 TERMS ( VARIABLES )
ARRAY A series of memory locations referenced by one name
CONSTANT A fixed value referenced by a single name
FACTORING Pulling out common steps of a program into own words
FETCH To retrieve a value from a memory location
INDEX A number indicating a location within an array
INITIALIZE The setting of an array to known values
OFFSET An value added to address, pointing into an array
STORE Placing a value into memory location
VARIABLE Memory location for storing changing values
CHAPTER 8 VARIABLES AND ARRAYS
Most programs, including tutor.blk, need to use variables
and constants. Variables are pointers, temporary sums, or any
values that can be changed. Constants are values that are used
by programs and generally are not changed. Forth requires these
locations to be declared before use, using either VARIABLE or
CONSTANT inplace of the : . This tells the compiler to define a
word and allocate memory for it. Constants take a value off the
stack and place it in the allocated memory location. When these
words are used they return their address to the stack for use
by ! @ ? or +! .
! means to store a value in location of address on stack with
value below it. @ gets or fetches value from address on stack.
? is a combination of @ and . to get and print a value. +! adds
the number below the address on the stack, to the location of
address.
There are double words for variables: 2VARIABLE, constants:
2CONSTANT, as well as 2! to store a double length variable, and
2@ to fetch double length variables or constants.
Many programs use arrays, or a number of memory locations
that can contain values. Arrays can have fixed values, as in a
table of phone numbers, or variables which can keep count of a
number of events. To create an array in Forth use the word
CREATE and the name assigned to it. The compiler will set as
many memory locations aside as you ALLOT to it. An array of two
will be defined, unless you allot more. Placing values in or out
of an array is the same as any variable, it is just the address
provided will be for the first entry in the array. If you want
the seventh item, you must increment the address by 14 as each
location is 2 addresses in length. The same is true for ALLOT
you must double the value (10 ALLOT creates 5 16bit locations).
An example of an array is your programs memory. Forth has a
word for looking at this large array, it is DUMP. Place the
starting address on the stack, next push the count or how far
you want displayed, then DUMP and watch what is there.
As we said before a byte is 8 bits and is the smallest way
some machines handle information. You can get data from or into
an array in 8 bits at a time. Arrays of characters are all 8 bit
entries. C! stores 8 bits, while C@ fetch 8 bits, just remember
to set the address one step for each location in the array.
The , is used to create a constant with values entered at
time of compilation. Use values and a , for each entry instead
allotting space (do not forget the last , ).
Variables, constants, and arrays are easy to create in Forth
and just as easy to use. For a problem we can use the topic of
last chapter and this to create a telephone listing or array.
This array should contain numbers and when queried with an
index produce formatted output. Lets give it a try...
Scr # 73 C:TUTOR.BLK
CHAPTER 9 GLOSSARY ( FORTH ENGINE )
' xxx ( - a ) Returns dictionary address of xxx
['] ( - a ) Generates literal number used inside the words
definition of the next word used in definition
EXECUTE (a -) Executes the dictionary entry at address a
@EXECUTE (a -) Executes entry pointed to at address a
>BODY (cfa -pfa) Returns parameter field from compilation addr
EXIT ( -- ) Terminates or returns from definition
QUIT ( -- ) Clears stack, gets control, no ok prompt
ABORT ( -- ) Clears data stack then does QUIT
DP ( - a) Returns address of dictionary pointer
HERE ( -- a) Next available dictionary location
PAD ( -- a) Beginning address of character string buffer
SP@ ( -- a) Pointer to top of data stack
S0 ( -- a) Returns address of bottom of data stack
TIB ( -- a) Returns address of text input buffer
FORTH ( -- ) Makes FORTH context vocabulary
EDITOR ( -- ) Makes EDITOR context vocabulary
CONTEXT ( - a) Returns address of search order variable
CURRENT ( - a) Returns address of new word vocabulary ( vocs)
DEFINITIONS Sets the current vocs to context vocs
CHAPTER 9 TERMS ( FORTH ENGINE )
ADDRESS INTERPRETER Interprets the address from the colon
definitions and executes them
BODY The code and parameter of a dictionary entry
BOOT The basic starting portion of Forth, precompiled Forth
CFA Address of code field in a dictionary entry
CONTROL TASK A task that does not converse with Forth
CODE POINTER FIELD The entry in the dictionary that points to
the run time code
DEFINING WORD A Forth word that creates a dictionary entry
ELECTIVES Optional blocks of words like floating point math
FORWARD REFERENCE Refering to undefined words
HEAD Name and link field of dictionary entry
LINK FIELD Pointer to next entry of vocabulary, search order
NAME FIELD Location of name of word, includes word length
PAD Area of memory for intermediate data storage
PARAMETER FIELD The area of the definition in which the
actual code or values are contained
PFA The address of the first entry of parmeter field
PRECOMPILED PORTION The Forth system loaded at boot time with
all dictionary words and terms ready to use
RUN-TIME CODE Usually the actual code that is the word
SYSTEM VARIABLES Variables usuable by all users in system
TASK A area of memory set aside for a given activity
TERMINAL TASK A task that has a user talking to Forth
TEXT INPUT BUFFER Memory area containing terminal input data
USER VARIABLE Variable accessible by one user only
VECTORED EXECUTION Executing words by going to a pointer
VOCABULARY An independent linked list of words. In F83
SHADOW EDITOR HIDDEN BUG ROOT USER ASSEMBLER
DOS FORTH are vocabularies. Use VOCS to see
this list of vocabularies.
CHAPTER 9 FORTH ENGINE
Forth is a THREADED programing language. This means that a
action amounts to performing one instruction contained within
an instruction. Words which perform the actions are made up of
lists of addresses of words that together will perform the
desired action. These words within words can also have words
within them. If you follow the actual actions it is like a
thread linking all the actions together.
In comparing Forth to assembly language it would be like a
routine calling a subroutine which calls a subroutine and can
call more till it finally does something and then returns back
through each of the called routines. That final actual code
performing actions makes up the KERNAL of the system.
The kernal is written in native code of the machine it is
on. The kernal creates the stack and basic operations of Forth.
Utilities are then written using Forth words, building blocks
until a full system is created. To move the system to another
type of processor requires rewritting only the native code of
the inner most kernal, not the utilities.
Most computers are made up of CPU or central processor units
which have a number of registers and instructions to move data
between registers and the outside world. What Forth does is to
create an artificial processor in software that can be moved
to different machines. This created processor can give the user
near assembly language performance, while being transportable.
In F83 we have the normal kernal using the Forth-83 word set
as well as many utilities, which create a full system. All these
abilities are contained in the dictionary. When Forth words are
interpreted, FIND searches the dictionary for a match, and then
EXECUTES the instructions. What is passed is not actual words
but their address. An word contains addresses or machine code.
The kernal items are mostly code, while utilities are mostly
addresses pointing to code containing words.
Forth has several ways to handle words by the user, one way
is ' which returns the address of the word, use U. to see the
actual address of a word ( ' SEE U. ). What interpret does is '
the word then does EXECUTE on the address on the stack. This is
not the address of the first address of a dictionary entry, but
the third. Lets look at how words are arranged.
When you create or define a word, several entries in memory
are completed. The word name is stored, up to 32 characters in
F83, after a count of the length of the name. Next is the link
to the next item in the current vocabulary. This link tells the
interpreter where next to look if the current word is not a
match. After the link is the CODE FIELD ADDRESS or CFA. This is
what is returned by ' and points to the code or code intrepter.
The interpreter can be one of three types, variable, constant or
code. The variable and constant return address or values on to
the stack respectively. The code points to either actual machine
code if it is a kernal item, or more CFA's. What it points to is
called PARAMETER FIELD or PFA, and given the CFA >BODY will put
the PFA on the stack.
There are other actions that occur while the interpreter is
going through the PFA, mainly pushing the next PFA onto the
return stack. This is why use of the return stack must be done
within the : definition, not doing so destroys the pointer to
the next word. You can carefully handle this stack and cause
wanted results by dropping off pointers, use caution though!
You can officially leave a diffinition, using QUIT ABORT or
ABORT" any of these three end the operation. Generally these
ways are used inside of IF THEN or DO LOOPs checking for flags
or problems. When the last PFA is found the word EXIT is left.
This word removes the pointer from the return stack and this is
interpreted next. EXIT can not be used inside of DO LOOP as it
will return loop counters and not addresses.
There are some ideas and words that you should know which
relate to the memory map of a Forth system. Normally from low
memory up is the kernal, system variables, utilities, users
dictionary space, the PAD, DATA STACK, TIB, RETURN STACK, users
variables, and block buffers. The users dictionary grows toward
the PAD, while the DATA and RETURN stacks grow down toward low
memory. The stack is actually a pointer to memory locations and
is lowered each time an entry is made.
To find these locations in memory, use DP to find the last
or highest memory location free for new dictionary word entries.
DP is the pointer while HERE will place the pointer value on the
stack ( same as DP @ ). To find the true location of the stack
use SP@ and it will fetch the pointers value, while S0 will get
the starting address of the stack. In higher memory above the
data stack is the TIB or Text Input Buffer and it grows up
toward higher memory. TIB fetches the starting address of the
buffer. The input line interpreter reads this buffer to find out
what you have entered.
To improve speed of interpretation, the dictionary is sorted
into different lists or vocabularies. When in these vocabularies
Forth will only search those words through use of the linked
address value. Typing the name of a vocabulary puts you into
that linked list. These lists can be scanned consectatively if
the word is not found in the first list. VOCS will display the
list of current vocabualries, while CONTXET shows the search
order. CURRENT will print which VOCS you are now in. To see the
words contained in one of these list, enter DOS WORDS and you
will see all the dictionary entries that relate to the DOS ( and
are used by Forth when talking to the operating system).
Take the time now and do some exploring in F83. Reading the
file README will explain some of the system terms and show a
memory map of a typical 8080 Forth system. Try reading all the
VOCS and check CONTEXT before and after changing vocabularies.
Scr # 84 C:TUTOR.BLK
CHAPTER 10 GLOSSARY ( I/O )
UPDATE ( - ) Marks most recently used block as modified
SAVE-BUFFERS Writes all updated buffers to disk
FLUSH Does save-buffers then frees all buffers
EMPTY-BUFFERS Marks buffers as empty, all data is lost
BLOCK ( u - a) Put starting address of block u on stack
BUFFER ( u - a) Like block but does not load block from disk
TYPE ( a # -) Send # characters at addr a to output device
-TRAILING (a #1 - a #2) Changes byte count to reflect blanks
>TYPE ( a # -) TYPE for multiusers, puts string in PAD first
MOVE (a1 a2 # -) Moves # of cells from a1 to a2 (low > hi)
CMOVE (a1 a2 # -) Moves # of bytes from a1 to a2 (low > hi)
CMOVE> (a1 a2 #-) Moves # of bytes from a1 to a2 (hi > low)
BLANK ( a # -) Fill a with # of blank ASCII bytes
KEY ( - c) Put next available INPUTED ASCII char on stack
EXPECT (a # -) Awaits # chars or CR from KEY storing at a
SPAN ( - a) Addrs of number of chars stored by EXPECT
WORD (c - a) Puts one word from input stream into addrs a
COUNT (a -a+1 #) Changes stack values of string a for TYPE
>IN ( - a ) Variable with pointer to next free input space
BLK ( - a ) Variable pointing to active block, 0= TIB
CONVERT (ud1 a1 -ud2 a2) Convert ASCII string a1 to binary ud2
NUMBER ( a -d ) Convert ASCII string a to binary values d
-TEXT (a1 # a2-f) Flag true if no match in strings # long
-MATCH (d # s # -a f) Find match in stings s/d return addrs flag
" ( - a ) Returns address of compiled string
CHAPTER 10 TERMS ( I/O )
EXPECTING Stop computing and wait for keyboard input
RELATIVE POINTER An index into an array used with address to
find true location of data
SCANNING Searching ahead for given characters
SUPERSTRING A string within an array of strings
VIRTUAL STRING Use of disk storage as if it were real memory
CHAPTER 10 I/O
EMPTY-BUFFERS will clear all pointers without writting to
disk. Any data contained within the buffers is lost at the sake
of freeing all buffers for more data. Accessing these buffers
you use BLOCK to return the address of the first byte in the
numbered block. If the block is not already in memory, BLOCK
will force it to be read. BUFFER returns a blocks address but
will not force a read ( used within BLOCK).
We can get data into the system, either from the blocks or
from the input string (keyboard). As indicated before to output
characters to the terminal you use EMIT. To send strings you use
TYPE, with the count on top and string address below. TYPE will
print the characters including blanks, -TRAILING will return
without the blanks by changing the stack count, then use TYPE.
To get these strings into buffers or locations accessible to
our programs we can MOVE them around. MOVE copies 16 bit cells
from locations pointed to by the third stack item to the second
stack address, and will move the count value(top stack). CMOVE
does the same, but count is now byte moves or 8 bits at a time.
These move the data from low memory to higher memory and could
over write data yet to be moved. CMOVE> starts from the top or
high memory and moves data down, preventing garbage generation.
Forth has several ways of getting input from the keyboard
into the system. KEY is the basic single character input word.
KEY? flags if the keyboard has been used. EXPECT will wait and
then store a string of characters from the keyboard.
Once we have the data in the TIB, we now need to be able to
process it. WORD will scan a string until it finds a given
character and then moves this string to a new buffer with the
count (length of string) as the first address. We use COUNT to
add one to the address and push the count on the stack.
When performing your own control over Forth, you will want
more control than most programming languages provide. Many of
the string commands help you understand how Forth works, and
there are more pointers that may be of interest to you. >IN
tells where in the input string the interpreter is at, while BLK
indicates wether the system is taking input from the TIB or the
block buffers. If BLK is zero, input is from TIB, non zero is
block buffers.
There are two ways to compare strings looking for matches. The
-TEXT word compares two strings with a given length and will set
the flag false if they match. -MATCH searches for a match of one
string and its length within a second string of some length, if
a match is found the stack will contain the starting address of
the match and the flag set false (in that order).
The handling of strings is not difficult in Forth and in fact
you have more control over how to handle strings than any other
programming language. If Forth doesn't do what you want, just
write some word that does.
As a problem, try writing some words that find matches in
a block buffer and then change them to random words selected
from a second buffer, should be fun and produce some intersting
statements.
Scr # 92 C:TUTOR.BLK
CHAPTER 11 GLOSSARY ( EXTENDING )
DOES> ( -- a) Separates compile data from run-time portion
IMMEDIATE To be executed not compiled into the word
COMPILE xxx Compile word xxx address into definition
LITERAL A value pushed on stack by a word (binary)
[ Leaves compile mode
] Starts compile mode
[COMPILE] xxx Makes a immediate be treated as non-immediate
STATE ( -- a) True if compiling, false if interpreting
INTERPRET Perform text interpretation of input stream
CHAPTER 11 TERMS ( EXTENDING )
COMPILE-TIME The action of compiling or generating a new
dictionary entry, for later run-time use.
COMPILING WORD A word that has action only during the
compilation stage, to generate proper run-time action.
DEFINING WORD When executed defines a new dictionary entry
that may have compile-time and run-time parts.
IMMEDIATE WORD A word that gets executed during compilation
and not compiled into dictionary.
PRECEDENCE BIT The 16th bit, indicates wether a word should be
executed (immediadte) or compiled.
RUN-TIME The normal action which a word will take, which
is what the word DOES>, it's definition.
CHAPTER 11 EXTENDING
It is at this point that we find out how Forth works.
More important it is where we find out how to change Forth to
meet our needs. All of this is done by extending the dictionary
or when compared to other languages it would be like re-writting
the compiler so that it has new ways of handling the input. You
can never NOT do something in Forth, it may not at present have
a way of handling your desires, but learn its insides and you
can make it do anything.
We should remember that Forth has two states or actions
possible. The first is interpreting, the other compiling. In the
interpretive mode we take data from a source and perform actions
much like basic reads lines of code and acts on them. The other
mode creates new words for the interpreter to use. It would be
like creating a new print command in basic (something you can't
do).
The words we use in the interpret mode have all been defined
and compiled in the kernal of Forth. The UTILITY.BLK and CPU8088
.BLK have most of the source code words for you to look over. In
looking these words over we will see two possible actions that
can take place in creating the dictionary words. These two are
compile-time and run-time activities. .
When compiling if we used Forth words that act on the
input data immediately, we would get garbage. That is it would
output data as the word was being created, not when we are
invoking it. Therefore we need to have words that control when
words do their thing.
CREATE is the word that creates the dicitonary entry and
puts in link and code addresses. This word is used to define
words like CONSTANT and VARIABLE. These words when we use them
will CREATE a dictionary input using the name we pass at that
time. CREATE doesn't do anything at the time it is used in the
defined word, only when we invoke it as part of a new defined
word. Now if we want the new defined word that was created by
using a word with CREATE in it, we use DOES>. DOES> separates
the creation from the activity when it is invoked. This is the
difference between compile-time and run-time actions.
Compile-time actions occur when the word is being created,
while run-time actions occur when the word is being interpreted.
It is important to understand the two different states of Forth
activities. You compile words into the dictionary which when
they get invoked will perform certain activities. To compile
these words may require some actions which are different from
the actions that occur at run-time (interpretation).
Interpretation occurs at all times, it just that some of the
interpreting is used to make new dictionary entries and some is
used to handle screen output. You don't want the two actions to
become confussed.
F83 has defined two words which can help show the difference
between these two states ." and .( The ." will store a string
that is printed when the word is invoke as in error messages.
The .( will print the string only while the word is being
compiled, or as I have used in the load screen to TUTOR it tells
you to wait while it is loading new words.
If we want to compute some values that later will be part of
the new defined word as LITERAL values we would use [ and ] .
The [ means interpret now, while ] means to stop interpreting
and resume compiling the word. If you are compiling directly
from the keyboard ] will continue compilation after a carriage
return.
The word IMMEDIATE means that this word is used within a
compilation to do its action immediately. The opposite of this
is [COMPILE] which delays compiling of the word till used in an
other words compilation.
Keeping track of when and what is being compiled and
interpreted takes some time and practice. Use the book for most
of this discussion. The samples and charts of when and how the
dictionary is changed is too complex for this simple tutorial.
To really understand Forth, you must use it and play with it
understanding how to adapt it to your style of programming. F83
and Forth together should be able to solve programming problems
with ease once you understand it.
ENJOY.
Scr # 99 C:TUTOR.BLK
== Source ==
Screen 0 not modified
0 (INTRO TEXT FOR SCREEN ZERO BDK112186)
1 ****************************************************************
2 ****************************************************************
3 ****************************************************************
4 ***** ******
5 ***** F83 TUTOR AND HELP PROGRAM ******
6 ***** F83 TUTOR AND HELP PROGRAM ******
7 ***** ******
8 ***** ******
9 ***** Written by Bill Kibler ******
10 ***** PO BOX 487 Cedarville, CA 96104 ******
11 ***** ******
12 ***** ALL Commercial rights reserved ******
13 ***** ******
14 ****************************************************************
15 ****************************************************************
Screen 1 not modified
0 ( LOAD BLOCK AND START OF TUROR PROGRAM BDK012387)
1 53 load 23 tree 15 spaces
2 .( PLEASE WAIT WHILE LOADING TUTOR SCREENS..TUTOR.BLK )
3 CR CR CR CR CR ( variables and display routines )
4 VARIABLE ETUTOR ( END DISPLAYING TUTOR SCREENS )
5 VARIABLE STUTOR ( BEGINING SCREEN OF CURRENT GROUP )
6 VARIABLE NTUTOR ( NEXT TUTOR SCREEN OF GROUP )
7 : L$$K DUP 36 = IF 1 ETUTOR ! THEN ; ( CHECK FOR $$ )
8 : DISPLAY ( DISPLAY SCREEN OF TEXT )
9 1 ?ENOUGH DUP SCR ! L/SCR 1
10 DO 5 SPACES
11 DUP BLOCK I C/L * + C/L
12 TUCK PAD SWAP CMOVE PAD SWAP ( >TYPE WITHOUT THE TYPE )
13 0 ?DO DUP C@ L$$K EMIT 1+ LOOP DROP ( TYPE WITH L$$K )
14 CR KEY? ?LEAVE LOOP DROP ;
15 -->
Screen 2 not modified
0 ( go get screens of information - gotutor tutor bdk012387)
1 : WTPRT ." CURRENT SCREEN IS " SCR ? 2 SPACES ." ESC = EXIT "
2 2 SPACES ." USE SPACE BAR FOR NEXT SCREEN " ;
3 : ESCCHK DUP 27 = IF 1 ETUTOR ! 32 THEN ; ( SET ESC FLAG )
4 : WAIT WTPRT 13 EMIT ( PRINT THEN CR WITHOUT LF )
5 BEGIN KEY ESCCHK 32 = UNTIL ; ( LOOP TIL SPACE KEY )
6 : GOTUTOR ( DISPLAYS SCREEN ON STACK THEN WAITS )
7 CR DUP SCR ! 15 SPACES .SCR CR
8 BEGIN DISPLAY WAIT NTUTOR @ 1 + DUP
9 DUP NTUTOR ! 1 ETUTOR @ = UNTIL CR CR 3 SPACES
10 ." REPT = REPEAT LAST LESSON ...GET = NEXT LESSON "
11 ." MENU = MENU " CR CR CR ;
12 : TUTOR ( STORE SCREEN POINTERS THEN GOTUTOR )
13 0 ETUTOR !
14 DUP DUP STUTOR ! NTUTOR ! GOTUTOR ;
15 -->
Screen 3 not modified
0 ( INITIALIZE AND START THE LOOPS..GET..REPT.. bdk012987)
1
2 : GET ( GO GET NEXT GROUP OF SCREENS )
3 NTUTOR @ TUTOR ;
4
5 : REPT ( GO BACK AND REPEAT SET OF SCREENS )
6 STUTOR @ TUTOR ;
7
8 : START-TUTOR ( START WITH FIRST SCREEN OF TUTOR )
9 10 TUTOR ;
10
11 : HELP ( GIVE INTRO MESSAGE )
12 6 TUTOR ;
13
14 -->
15
Screen 4 not modified
0 ( DEFINING MODULES OF INFORMATION..... bdk012387)
1 : INTRO 10 TUTOR ;
2 : CHP1 12 TUTOR ;
3 : CHP2 18 TUTOR ;
4 : CHP3 25 TUTOR ;
5 : CHP4 34 TUTOR ;
6 : CHP5 40 TUTOR ;
7 : CHP6 48 TUTOR ;
8 : CHP7 55 TUTOR ;
9 : CHP8 66 TUTOR ;
10 : CHP9 73 TUTOR ;
11 : CHP10 84 TUTOR ;
12 : CHP11 92 TUTOR ;
13
14 -->
15
Screen 5 not modified
0 ( MORE ROOM FOR LESSON WORDS.... bdk012387)
1
2 : MENU 9 DISPLAY ; ( will display infor screen )
3
4
5
6
7
8
9 : PRTSCR CR ." CURRENT GET SCREEN IS " NTUTOR @ .
10 CR ." REPT SCREEN OF INFORMATION IS " STUTOR @ . CR ;
11
12
13
14 HELP
15
Screen 6 not modified
0 ( PRINT SCREENS FOR TUTOR INFORMATION... bdk012887)
1
2 FORTH-83 TUTOR PROGRAM AND HELP SCREENS
3 WRITTEN BY BILL KIBLER
4 (c) 1987
5 ALL COMMERCIAL RIGHTS RESERVED
6
7
8 This program will help beginners and past FORTH users
9 alike. The screens contain information on FORTH-83 and are
10 related to the book " STARTING FORTH " by Leo Brodie, which
11 should be used as a textbook with this program. Each chapter
12 or series of screens is organized to present the words used in
13 the chapter in a glossary form. Forth users will find this
14 glossary important to see the differences between F83 and other
15 versions. Typing HELP will repeat these screens, then type
Screen 7 not modified
0 ( second intro screen with list of words... bdk012887)
1 the chapter number for the area of help needed. Typing ESC key
2 will exit the screens and return to the system prompt. GET will
3 display next chapter of information, while REPT will start
4 with the first screen of the chapter again. START-TUTOR will
5 start with the introduction chapter.
6 NEW F83 WORDS
7 The following words are important utilities in F83 and may be
8 different from previous versions. WORDS will display a list of
9 F83 words used. OPEN allows use of an existing file, 10 MORE is
10 used to add 10 screens, and 30 CREATE-FILE NAME.BLK (opens 30
11 screens). INDEX displays a list of line 0, 1 20 INDEX will list
12 screens 1 to 20. 1 30 SHOW will print 6 screens to a page on
13 your printer in condensed mode ( use: ' EPSON IS INIT-PR for
14 epson printers). 1 30 TRIAD prints three to a page if condensed
15 print is not available. 1 30 SHADOW SHOW will print both the
Screen 8 not modified
0 ( THIRD PRINT SCREEN OF TUTOR INFORMATION..... bdk013087)
1 regular screens and the information screens on a page (not used
2 in TUTOR but in UTILITY.BLK). SEE xxxx disassembles the word
3 xxxx, while VIEW will open the source file ( on A: drive) and
4 list the screen it is in. VOCS will list the vocabularies in
5 the dictionary, while ORDER displays the path of the directory
6 search. Use DOS WORDS to see a list of the DOS dictionary words.
7 CAPACITY will print the number of screens in a open file. A L
8 will toggle between the shadow and the source screens. N L will
9 display the next screen, L will list current screen, B L will
10 list previous screen. 1 EDIT will invoke the line editor with
11 screen 1 ready to edit. 0 NEW will start editing at line 0
12 and allow the text to be entered one line after the other. HEX
13 100 80 DUMP will do a hex dump of memory location 100h to 180h.
14 DEBUG LIST will allow stepping through list when used next as
15 in 1 LIST. Use BYE to exit to DOS.
Screen 9 not modified
0 ( last intro screen with list of words... bdk013087)
1
2 TUTOR WORDS
3 INTRO = introduction CHP1 = fundamentals
4 CHP2 = RPN and STACK CHP3 = editor commands
5 CHP4 = conditionals, nests CHP5 = fixed point operations
6 CHP6 = loops ( & nested) CHP7 = number types
7 CHP8 = var. const. arrays CHP9 = F83 structure
8 CHP10= Input/Output CHP11= extensions
9
10 GET = next chapter REPT = begin chapter again
11 HELP = repeat these screens START-TUTOR = start at INTRO
12 SPACE BAR = next screen ESC = stops display
13 BYE = EXITS to DOS MENU = displays this screen
14 PRTSCR = GET and REPT pointers
15 $$
Screen 10 not modified
0 (forth tutor program introduction to brodie.... bbdk011687)
1 INTODUCTION
2 Forth is a stack oriented language, a hardware independent
3 programming language and operating system. F-83 is based on the
4 Forth-83 Standard with enhancements to make it a full operating
5 environment.
6 F-83 contains the Forth-83 word set, plus words for
7 debugging, editing, disassembly, assembly, DOS functions and a
8 multitasking system.
9 The F-83 system is available on all standard computers
10 currently being manufactured; providing a complete set of
11 portable system utilities that are independent of hardware.
12 Use this tutor program to learn F-83 and the differences
13 between this version and past or commercial versions of Forth.
14 HELP will display a summary of information about F-83 and this
15 tutor program.
Screen 11 not modified
0 ( second intro to brodie... bdk011687)
1 This tutorial uses the well known and popular text "STARING
2 FORTH" by Leo Brodie. Many references are made to the text and
3 it should be used to obtain detailed information about Forth.
4 The program does not cover everything about F83, but only
5 attempts to provide on line help information and instruction.
6 There are two versions of "STARTING FORTH" currently being
7 used. The first edition did not contain any reference to F83
8 and was printed before 1982. This tutorial will help people with
9 the first edition see the differences between FIG, Forth-79
10 and the new F83 (Forth-83).
11 The second edition is mostly the same information with
12 changes for the newer Forth-83. Some minor text changes have
13 been added to improve the understanding of some terms. All the
14 other changes are related to the new or different commands used
15 by F83 or contained in the Forth-83 standard. $$
Screen 12 not modified
0 ( chapter 1 intro to stack operation bdk012887)
1 GLOSSARY OF CHAPTER 1
2 : xxx yyy ; ( - ) Creates word xxx which does word yyy
3 CR ( -- ) Do a carriage return and line feed
4 SPACES (n -- ) Print n number of spaces
5 SPACE ( -- ) Print one blank space
6 EMIT (c -- ) Transmit a character to output device
7 ." zzz" ( -- ) Print the output string zzz at terminal
8 + (n1 n2 -- sum) Adds n1 to n2 and leaves sum on stack
9 . (n -- ) Print number on top of stack followed by space
10 ( xxx) ( - ) Comment, ignored by the text interpreter
11 TERMS IN CHAPTER 1
12 COMPILE To generate a dictionary word
13 DICTIONARY Forths list of words or operations
14 EXECUTE To do the operations a word stands for
15 EXTENSIBILITY Ability to modify, add or change words
Screen 13 not modified
0 ( CHAPTER 1 MORE WORDS AND TERMS bdk011987)
1 GLOSSARY A list of words defined and explaned in Forth terms
2 INFIX NOTATION Using operators between operands
3 INPUT STREAM Text to be read by TEXT interpreter
4 INTERPRET To compare input text to FORTH words
5 LIFO Last In First Out..how the stack works
6 POSTFIX OPERATION The way FORTH operates..RPN
7 STACK A section of memory used as a data stack
8 STACK OVERFLOW Stack operations used all allocated stack
9 STACK UNDERFLOW Operations tried to read data from empty stack
10 WORD The name of a FORTH definition
11
12 CHAPTER 1 FUNDAMENTAL FORTH
13 FORTH has two main features, EXTENSIBILITY and INTERACTION.
14 New functions are added to the language by creating new words
15 and adding them to the dictionary of existing words. This
Screen 14 not modified
0 ( chapter 1 continued fundamentals bdk012887)
1 operation is called extending the dictionary, and thus the term
2 "extensibility". As each new word is created it can be used
3 immeadiately to see if it functions properly. This instant
4 adding and execution of the word is the reason behind the term
5 "interactive".
6 When Forth is waiting for your input, your terminal will
7 have displayed "ok" on the previous line. This means the
8 interpreter is waiting for your next input. That input can
9 be a direct command such as 42 EMIT which will output the
10 ASCII character * (star) to your terminal.
11 To make a new word for the dictionary, you need to follow
12 the definition structure, this is a colon (:), a space, the
13 name of your word (star), a space, the definitions, a space,
14 and lastly a semicolon indicating the end of the word. Follow
15 the semicolon (;) with the return key and the action you have
Screen 15 not modified
0 ( more fundamentals of forth..chapter 1 bdk011287)
1 defined will take place.
2 FORTH is stack oriented, the input string is processed
3 and input which is not a defined word, is assumed to be a
4 numeric input and is pushed onto the stack. Numbers are pushed
5 until a word is found, where upon the functions defined will be
6 performed on the numbers on the stack from the top down.
7 In the line 2 4 + . we have the numbers 2 and 4, a plus sign
8 to add the two number on the stack, and a period which prints
9 the top value on the stack. This means 2 is pushed first, then
10 4 is on top, the + sign is interpreted and Forth adds the 2 and
11 4 getting 6, and places six on the stack. The next command, the
12 . removes the 6 from the stack and converts it to the ASCII
13 equivalent, before outputting it to the screen. The screen can
14 not print numbers directly, but there is a standard number which
15 is used to represent the number 6, this is ASCII number 54.
Screen 16 not modified
0 ( more fundamental forth chapter 1 bdk011987)
1 To display the manner in which your word handles the stack
2 a standardized convention is used. The ( n1 n2 -- sum ) is
3 used to indicate that the first number ( n1 ) is push on the
4 stack first, followed by n2, the second number. Forth then
5 ( -- ) reads the word and performs the function, placing the
6 results ( sum ) on the stack. The right most item is the one
7 currently on top of the stack, or you read from left to right
8 which corresponds to bottom of stack to the top.
9 This has been a brief summary of fundamental forth as was
10 presented in "Starting Forth", please study it for more details.
11 You can now try some of the samples listed in the book, just
12 wait for the "ok" prompt after you hit the space bar again. Try
13 inputting the line displayed below, to define the new word GREET
14 : GREET CR ." HELLO, I SPEAK FORTH " ;
15
Screen 17 not modified
0 ( space for more work problems.... bdk012187)
1
2 Create a word that asks for your name.
3
4
5
6
7
8
9
10
11
12
13
14
15 ( $$ )
Screen 18 not modified
0 ( chapter 2 glossary of new words... bdk010587)
1 GLOSSARY OF CHAPTER 2
2 + (n1 n2 -- sum ) adds two stack items, leave sum on top
3 - (n1 n2 -- diff) subtract n2 from n1, results on top
4 * (n1 n2 -- prod) multiplies n1 times n2
5 / (n1 n2 -- quot) divides n1 by n2, quotient on top
6 /MOD (n1 n2 -- u-rem u-quot)
7 divides and leaves quot on top, remainder below it
8 MOD (n1 n2 -- u-rem) divides and leaves only the remainder
9 SWAP (n1 n2 -- n2 n1) swap the order of the top two items
10 DUP (n -- n n) make the top two items the same
11 OVER (n1 n2 -- n1 n2 n1) copy second item on top of stack
12 ROT (n1 n2 n3 -- n2 n3 n1) puts third item on top of stack
13 DROP (n -- ) throw away top stack item
14 2SWAP (d1 d2 -- d2 d1) swap the top two PAIRS of numbers
15 2DUP (d -- d d) duplicates the top PAIRS of numbers
Screen 19 not modified
0 ( chapter 2 more words and start of text bdk010587)
1 2OVER (d1 d2 -- d1 d2 d1) copy second PAIR, push on top
2 2DROP (d -- ) drop the top PAIR of number off of stack
3
4 TERMS IN CHAPTER 2
5 DOUBLE LENGTH NUMBERS Twice the length of the hardwares normal
6 word length. In 16 bit words that would be a 32 bit number
7 and typically is a value of plus or minus 2 Billion
8
9 SINGLE LENGTH NUMBERS The normal length of words used by this
10 version of Forth, typically -32768 to +32767. These are
11 intergers or whole numbers (no decimal points allowed)
12
13
14
15
Screen 20 not modified
0 ( review of chapter 2 subjects and text bdk011687)
1 Chapter 2 How to get results
2
3 Forth arithmetic is similar to a number of calculators one
4 can buy. These calculator are usually called RPN or Reverse
5 Pollish Notation calculators. They operate on a stack type
6 structure and require at least two items on the stack before
7 you can add, subract, multiply, or divide. Forth uses the +
8 (plus) sign for addition, - (minus) sign for subtraction, *
9 (star) for multiplication, and / (slash) for division.
10 These procedures are used with interger math, or whole
11 numbers only. On most Forths these are +32767 to -32768. This
12 interger math requires some thought on the users view point.
13 Numbers larger than these require other words or double length
14 operators, which are covered in chapter 7. For now lets look at
15 using whole numbers in division.
Screen 21 not modified
0 ( chpt2 text continued div mul bdk011287)
1 Interger math requires more than one step when dividing. What
2 happens is the results and the remainder are treated as two
3 separate whole numbers. The operation 20 4 / will divide 4 into
4 20 and produce the whole results 5. 22 4 / will also produce
5 the same answer 5, the remainder 2 is lost. If we use 22 4 MOD
6 we get remainder only 2. To get both the results and remainder
7 you can use /MOD as in 22 4 /MOD puts 5 on top of the stack
8 the remainder below it. Remeber the . will print the top stack
9 item and make the second item the top element.
10 In most math operations there is a means of specifing the
11 order of operations. With forth being stack oriented order is
12 determined by placement in the stack. A infix presentation of
13 4+(17*12) would be presented in forth as 17 12 * 4 + . with
14 208 being displayed. Numbers are pushed onto the stack while
15 the operators are performed in a left to right manner. We see
Screen 22 not modified
0 ( chptr 2 continued order and swaps... bdk011287)
1 that 4 17 12 * + is the same as the previous problem. The * is
2 performed first on the top items (17 and 12) then the + is
3 used on the top (204) element and the second, now 4. The . will
4 print the results of 208.
5 There are several ways of handling the stack order and making
6 changes to it. If you want the results of a math operation to be
7 printed but still available for the next operation, you DUP
8 the results before printing it. DUP takes and pushes the top
9 item on the stack down one and makes a copy of it on the top of
10 the stack. OVER will make a copy of the second item and place it
11 on the top, or DUP the second item. To reverse the top two items
12 on the stack you would use SWAP. To get the third item on top
13 and make items 1 and 2 now 2 and 3 respectiviely you use ROT. If
14 you want to remove the top item we just DROP it off the stack.
15 Later on we will deal with double length number (larger than
Screen 23 not modified
0 ( last chapter 2 with sample problem bdk012187)
1 32768), we also have double word or item operators, these are
2 2SWAP, 2DUP, 2OVER, 2DROP. These perform the same operation as
3 their single counterparts, they just work on two stack items at
4 a time. 2DROP will DROP the first and second items off the
5 stack.
6 For more samples of these operations check the book, or play
7 around with forth when you see the ok after this screen. Here
8 are some sample problems:
9 if a=4 and b=8 what is a*(a+b) there are two ways to do this
10 if c=3 then evaluate ab - bc again two ways here too
11
12 make a new word that will return the number of kilometers when
13 the top stack item is number of miles.
14
15 Try these problems or make up some of your own...
Screen 24 not modified
0 ( problem space..... bdk011987)
1
2 In this screen...number 24
3
4
5
6
7
8
9
10
11
12
13
14
15 ( $$ )
Screen 25 not modified
0 ( chapter 3 glossary for editor words bdk011987)
1 CHAPTER 3 GLOSSARY ( EDITOR )
2
3 LIST (n -) Display screen n and make it current screen
4 LOAD (n -) Load n screen and interpret into dictionary
5 FLUSH SAVE-BUFFERS and de-allocate buffers in memory
6 SAVE-BUFFERS Write all buffers to disk files ( also use W )
7 UPDATE Mark current screen for save to disk
8 L Display current screen
9 N L Display Next screen
10 B L Display previous (Back one) screen
11 A L Toggle between current and shadow screens
12 T (n -) Make n the current line to edit
13 P xxxx Put the string xxx in the current line
14 U xxxx Insert the string xxxx under the current line
15 K ( -) Exchanges the contents of insert and find buffers
Screen 26 not modified
0 ( more chpt 3 glossary words...editor bdk011187)
1 X Delete current line
2 NEW (n -) Input multiple lines starting at n
3 F xxxx Find and move to END of xxxx
4 D xxxx Delete string xxxx and leave cursor at string
5 TILL xxxx Delete all text from cursor to end of xxxx
6 J xxxx Delete till begining of string xxxx
7 EDIT (n -) Invokes editor on n screen
8 EDITOR Makes the editor vocabulary current vocabulary
9 DONE Do flush and return from editor vocabulary
10 ED Return to editing current screen
11 FIX xxxx Find xxxx in unknown screen and start editing it
12 OPEN xxxx Open file xxxx.xxx and make it current file
13 MORE (n -) Add n more screens to the end of current file
14 COPY Copy screens from one file to another
15 CONVEY Move screens around within file
Screen 27 not modified
0 ( more glossary words..last screen of them... bdk011987)
1 FORGET name Removes all word definitions back to name
2 THRU (lo hi -) Loads all blocks between lo and hi inclusive
3 TRIAD (n -) Print three blocks around n on a page
4 SHOW (lo hi -) Print 6 blocks to a page in condensed mode
5 VIEW name Find name in source screen and list it
6 WIPE ( -) Blanks the entire screen when editing
7 G ( blk ln -) Gets copy of line from block and insert above
8 current line pushing lines down
9 BRING ( blk lo hi -) GETS range of lines
10 S xxx (n - n) Searches for xxx in blocks n up if found n on top
11 LISTING name Print entire open file including shadows
12 KT xxx Put all text between cursor and xxx in insert buffer
13 O xxx Overwrites xxx onto text of current line
14 SPLIT Breaks current line in two at the cursor
15 JOIN Puts a copy of next line after the cursor
Screen 28 not modified
0 ( review of chpt 3 terms bdk012887)
1 QUIT Exit editor WITHOUT updating buffers to disk
2
3 CHAPTER 3 TERMS ( EDITOR )
4 BLOCK The means of which files are divided, 1024 characters
5 is one block (BLK) and is used as screens (SCR) in forth
6 BUFFER Temporary space set aside in memory to hold BLKs or SCRs
7 DISK A short term for floppy disk and data stored there
8 EDITOR The forth vocabulary that contains words used by editor
9 FIND BUFFER The buffer containing the find string
10 INSERT BUFFER The buffer containing the insert string
11 LOAD BLOCK The block which loads other blocks or screens
12 NULL DEFINITION A word that has no action, a marker
13 OVERLAY Data that will replace previous data or words
14 POINTER A value or location that points to other data
15 SOURCE TEXT The text which is the original definition of a word
Screen 29 not modified
0 ( chptr 3 text, information on editing bdk011987)
1
2 CHAPTER 3 THE EDITOR
3 Forth contains a built in line or screen editor. This editor
4 is not like some commercial word processors, but more like the
5 line editors which come with most operating systems. Forth
6 stores all the source code for itself as plain text in screens.
7 The plain text statements are compiled through a special META
8 compiler to produce the F83 machine code program. Two files
9 contain most of the source code for F83, they are UTILITY.BLK
10 and KERNELxx.BLK. UTILITY contains the higher level utility
11 functions which you use, such as the editor's source code. The
12 KERNELxx contains all the screens necessary for making the main
13 F83 kernel as would be used on xx processor. The xx stands
14 for 86, a short way of saying 8088/86 CPU which is used in the
15 IBM PC line of computers.
Screen 30 not modified
0 ( chpt 3 continued editor / changing screens bdk011987)
1 Suppose you want to change some printer directives, which
2 are in the utility files. Currently F83 uses Epson printer codes
3 when invoking condensed modes of printing. Your printer uses
4 different codes from the Epson. To find the screen where this
5 code is we use FIX EPSON, after the file has been opened using
6 OPEN UTILITY.BLK. This will display the screen (44) which has
7 the source code word EPSON, and position the editor after this
8 word. You can now use the editor commands to change the control
9 code invoked using the word EPSON. When you have made the change
10 DONE will exit the editor saving changes. Reloading the sytem
11 will give you the new printer commands. Also you could have
12 entered the minor changes directly from the terminal, but you
13 would have to do this each time you loaded the system.
14 In creating this tutor program, I have created a number of
15 blank blocks by typing 30 CREATE-FILE TUTOR.BLK. This then
Screen 31 not modified
0 ( more chpt 3 editor and editing files bdk011287)
1 allows me to do 1 EDIT and start creating the source code for
2 this program. The editor will then ask me for the ID........
3 and I will type my initials and current date. Becuse not all
4 forths reconize the back slash as comment line I use the ) as my
5 last item in the ID line. I start my screen with 0 NEW and will
6 type the first entry starting with a ( indicating a comment
7 is next. At this point you can type text one line after the
8 other, watching for the end of the line, the editor does not. 2
9 blank lines denotes end of NEW lines and you can then go back
10 and correct any mistakes.
11 Some samples of editing are; 3 T to select line 3 to edit.
12 Using P NOW will put NOW on line 3. U NEXT will put NEXT on line
13 4. If we type F T the cursor will be after the T on line 4. Now
14 you can type I TIME and line 4 will have NEXTTIME on it. To get
15 space between the Ts go 4 T again to get back to the begining of
Screen 32 not modified
0 ( more chpt 3 editing stuff... bdk012187)
1 the line, then F again (no T needed, buffer still has it) and
2 the cursor will be after the first T, do I with two spaces, the
3 return will then put a space between the Ts. You can of course
4 start a line with spaces or any items. The editor is not very
5 fancy, but it is in most versions of forth, meaning once learned
6 you can use it on any machine your forth is running on.
7 The instructions in the text are similar and do cover the
8 main commands used in most forth editors. F83 uses different
9 commands to move screens around. To load screens from the
10 utility file to this (which is already open and is the current
11 file) you would type FROM UTILITY.BLK 1 10 COPY this will copy
12 screen 1 of utility to screen 10 of TUTOR. Now to copy a string
13 of files you use CONVEY, such as 11 HOP 1 6 CONVEY to copy
14 screens 1 to 6 of TUTOR to 12 to 17 of TUTOR. The HOP means to
15 jump over 11 screen from the first one and start the copying
Screen 33 not modified
0 ( last screen of editing chpt 3... bdk012187)
1 there. 1 6 TO 12 CONVEY does the same as 11 HOP. For moving
2 screens between files, we would use the FROM UTILITY.BLK command
3 (after the OPEN TUTOR.BLK) and then 1 20 TO 30 CONVEY and this
4 will copy screens 1 to 20 of utility to 30 to 50 of tutor. You
5 may need to do 20 MORE first, which adds 20 empty screens to the
6 currently opened file.
7 If you have made backups of the TUTOR.BLK files, now would
8 be a good time to try editing. If you use 25 35 INDEX you will
9 find out which screens are blanks and you could use one of them.
10 The last screens are blank and ready for your playing around.
11 Try creating some new words and then LOAD the screen, which will
12 add the words to the dictionary. Another way to find empty
13 screens is 1 IND this will give the index or line 0 of each
14 screen starting with 1 until end of file is reached or you hit
15 the ESC key. Use QUIT if you dont want to save edits........ $$
Screen 34 not modified
0 ( chapter 4 glossary of decision words.... bbdk012887)
1 CHAPTER 4 GLOSSARY ( DECISIONS )
2
3 IF xxx IF: (f -) If f is true execute xxx, otherwise do yyy
4 ELSE yyy continue with zzz regardless, the ELSE yyy
5 THEN zzz is optional.
6 = (n1 n2 - f) Return a true flag if n1 and n2 are equal
7 <> (n1 n2 - dif) Returns true if n1 and n2 are not equal
8 < (n1 n2 - f) Returns true if n1 is less than n2
9 > (n1 n2 - f) Returns true if n1 is greater than n2
10 0= (n - f) Returns true if n equals zero
11 0< (n - f) Returns true if n is negative
12 0> (n - f) Returns true if n is positive
13 NOT (f - f) Reverse the results of the last test (0=)
14 AND (n1 n2 - and) Returns the logical AND of n1 and n2
15 OR (n1 n2 - or) Returns the logical OR of n1 and n2
Screen 35 not modified
0 ( chptr 4 more glossary and terms bdk011987)
1 ?DUP (n - nn) or (0 -0) Duplicate only if n is nonzero
2 ABORT" xxx " Abort operation and print xxx error message
3 (f -) also clear users stacks, if false no action
4 XOR (n1 n2 -xor) Exclusive or, true if both n not true
5
6 CHAPTER 4 TERMS ( DECISIONS )
7 ABORT Abruptly cease operation if procedure isn't acceptable
8 AND Output is true if both inputs are true
9 BRANCHING If input condition occurs jump to another routine
10 COMPARISON Check and flag if two items are the same
11 CONDITIONAL Different operation if flag true than when false
12 FLAG A variable when set equals true, reset equals false
13 LOGIC Using operators like AND, OR, NOT to make statements
14 NESTING Branching routines within branching routines
15 OR If either of two inputs are true the results is true
Screen 36 not modified
0 ( chptr 4 text on decisions.... bdk012887)
1
2 CHAPTER 4 DECISIONS, CONDITIONALS
3 In any computer language, terms are used to express math
4 forms and types. We like to compare items and say how one is
5 larger or smaller than an other. You may also base an action
6 on the results of such a comparison. Forth can also do the
7 same types of comparisons. We can tell forth to do something IF
8 some condition is met. The proper term for this is IF THEN
9 statements. To help make these comparisons there are several
10 operators we can use. They can be = for equals, < 2nd stack item
11 is less than top item, > 2nd item is greater than top item, 0=
12 the top item is equal to zero, 0< the top is less than zero, 0>
13 the top is greater than zero.
14 All of these operations depend on setting a FLAG variable.
15 This flag is a special indicator set as either true or false.
Screen 37 not modified
0 ( chptr 4 more text..logic, decisions... bdk012887)
1 IF THEN logic operations work by checking the flag to see if it
2 is true or false. If true THEN do xxx ELSE if false do zzz.
3 The IF statement can be any form of testing, including regular
4 math operations. A sample math operation is comparison <> where
5 if two items are the same, the results will be zero, and so the
6 flag will be set false (treated as subtraction).
7 There are non math operators that can do comparison based on
8 logic operations. These logic operators are AND, OR, and NOT.
9 AND sets the true flag if both stack items are also true, OR if
10 either stack items is true, while NOT reverses the flag setting.
11 Forth has some words which contain conditional tests within them
12 ABORT" and ?STACK. ABORT" print the statement contained within
13 the " " if the flag is set, leaves the current program and
14 resets all stacks before the Forth ok. ?STACK flags true if
15 the stack is empty, as when waiting for keyboard input.
Screen 38 not modified
0 ( some chptr 4 samples/ problems bdk012187)
1 Lets do a simple IF THEN routine to show the forth way of
2 handling conditionals. Lets test to see if a pupil answers a
3 question correctly when faced with four choices;
4 : ckansw ( check the answer and prompt accordingly )
5 DUP 1 = IF ." WRONG" CR 12 TUTOR ELSE
6 DUP 2 = IF ." CLOSE BUT REREAD QUESTION " ELSE
7 DUP 3 = IF ." GOOD CHOICE " ELSE
8 DUP 4 = IF ." BETTER LUCK NEXT TIME.. " ELSE
9 ." ENTER VALUE OF 1 2 3 or 4 ONLY "
10 THEN THEN THEN THEN DROP ;
11 This new word CKANSW, checks the item on top of the stack to see
12 if it matches or equals the value we want. If it does, print the
13 statement and then continue checking unitl last "then" is used.
14 When a non match occurs the prompt to enter a new value is now
15 displayed. Try your own conditional program in SCR # 39.....
Screen 39 not modified
0 ( some chptr 4 samples/ problems bdk011987)
1 ( here it is for you to change or use )
2
3 : ckansw ( check the answer and promt accordingly )
4 DUP 1 = IF ." WRONG" CR 12 TUTOR ELSE
5 DUP 2 = IF ." CLOSE BUT REREAD QUESTION " ELSE
6 DUP 3 = IF ." GOOD CHOICE " ELSE
7 DUP 4 = IF ." BETTER LUCK NEXT TIME.. " ELSE
8 ." ENTER VALUE OF 1 2 3 or 4 ONLY "
9 THEN THEN THEN THEN DROP ;
10
11
12
13
14
15 ( $$ )
Screen 40 not modified
0 ( chapter 5 glossary and interger math bdk011987)
1 CHAPTER 5 GLOSSARY ( INTERGER MATH )
2
3 1+ (n - n+1) Adds one to n
4 1- (n - n-1) Subtracts one from n
5 2+ (n - n+2) Adds two to n
6 2- (n - n-2) Subtracts two from n
7 2* (n - n*2) Multiplies n by two (shift left )
8 2/ (n - n/2) Divides n by two ( shift right )
9 ABS (n - |n|) Returns absolute value of n
10 NEGATE (n - -n) Changes the sign of n
11 MIN (n1 n2 - n-min) Returns the minimum n (either n1 or n2)
12 MAX (n1 n2 - n-max) Returns the maximum n (either n1 or n2)
13 >R (n - ) Place stack top item on return stack top
14 R> ( - n) Load top of stack with top of return stack
15 R@ ( - n) Make a copy of return stack, put on top of stack
Screen 41 not modified
0 ( More chapter 5 glossary and terms bdk012887)
1 */ (n1 n2 n3 - n) Multiplies then divides (n1*n2/n3)
2 */MOD (n1 n2 n3 - n-rem n-result) Get remainder, quotient on top
3
4
5 CHAPTER 5 TERMS ( INTERGER MATH )
6
7 Double length intermediate result Steps within an operation in
8 which the number size has twice the normal digits, inorder
9 to minimize errors.
10 Fractional arithmetic The handling of numbers without the
11 decimal point, using whole numbers, and later returning
12 the decimal point to its proper place. FIXED POINT can be
13 used inplace of fractional, they mean the same.
14 Floating point math Number containing the decimal point
15 and requiring adjustments before use by a computer.
Screen 42 not modified
0 ( chapter 5 terms and some text bdk011487)
1 Parameter stack The main data stack which is used to pass
2 data between operations of the forth machine. Generally
3 referred to simply as STACK or data stack.
4 Return stack The stack used by forth for keeping return
5 addresses on during operations. Can be used for holding
6 data from stack (parameter) only WITHIN a definition.
7 Always referred to as RETURN STACK, never stack!
8 Scaling The adjustment of floating-point numbers such that
9 all number are represent as intergers and with the same
10 relevant relationship in respect to the decimal point.
11
12
13
14
15
Screen 43 not modified
0 ( chapter 5 text INTERGER MATH math bdk012887)
1 CHAPTER 5 INTERGER MATH
2
3 Forth has a number of words that help perform math operations
4 quickly and easily. All of these operations work on INTERGER
5 MATH concepts, or interger numbers. Typically these are signed
6 numbers between +32768 and -32767. To add numbers that have a
7 decimal point we mentally multiply the number by a power of ten
8 enter those numbers and then replace the decimal point after the
9 operation. Some versions of Forth contain routines that will do
10 this for you, they are called floating point utilities. They can
11 slow down Forth considerably and waste memory.
12 Most Forth users prefer to use interger math for the speed
13 and memory savings. There are two words that help make interger
14 math easier */ (star slash) and */MOD (star slash MOD).
15 These words perform a multiply and then a divide (MOD produces
Screen 44 not modified
0 ( chapter 5 text fixed point bdk011987)
1 a remainder). Scaling is the method used in forth to change a
2 value so that it can be used in interger math. To use numbers
3 we scale them before use, then rescale the results back into the
4 same ratio. We can use PI not as 3.1416 but 31416 10000 / and
5 when used in a formula like PI * Dia for area we use */ as in
6 4 31416 10000 */ . and we get the area of a 4 foot circle. We
7 have made the results of 4 * 31416 be 10000 time larger than in
8 you would using PI as 3.1416, but by dividing our results by
9 10000 we return it to proper scale. PI however has more places
10 than four shown and will produce some error. There are fractions
11 which can represent a more accurate means of expressing this and
12 other numbers, they are called rational approximations, here are
13 a few: PI 355/ 113, SQRT of 2 19601/13860, SQRT of 3 18817/
14 10864, .001Deg./22-bit rev. 18118/21109.
15 To find our answer to the area of a 4 foot circle use the
Screen 45 not modified
0 ( chapter 5 more fixed point text bdk012887)
1 values of PI: 4 355 113 */ . this will be more accurate than
2 before. */ does not produce a remainder and the area of the last
3 problem is more than 12 square feet. Using */MOD will provide
4 the remainder as the second item on the stack. When using the
5 remainder we can then see the difference between dividing by
6 10000 and using 355/113, which is .0736. For a more detailed and
7 illustrated review of this topic check chapter 5 in STARTING
8 FORTH.
9 The return stack is used by Forth to store return addresses
10 of definitions (semicolons). It can be used within a definition
11 to help shuffle values around. A good example of that would be a
12 problem that uses a constant several times. Instead of dupping
13 the number and a ROT or SWAP it may be faster to copy it to the
14 return stack and make copies of it each time you need it. You
15 must remember to clear the return stack by the end or ; .
Screen 46 not modified
0 ( chpt 5 some quickies to help out bdk011987)
1 To help moving between the return stack and parameter stack
2 use >R to push on R< to get off and back onto the stack. R@
3 makes a copy of top of return stack and places it on top of
4 data stack.
5 In most programs there are several operations that occur
6 frequently and Forth has words to help out with them. Many a
7 time we need to add or subtract by 1 or 2, and thus the words
8 1+ 1- 2+ 2- 2* 2/ . Filtering of values is also important, so we
9 have ABS for absolute value, NEGATE for changing signs, MIN and
10 MAX to find the relationship between 2 values.
11 Try these problems or write a new word in screen 47 for each
12 of these inputs,0 degrees F and 45 degrees C. Use these formulas
13 C= (f-32)/1.8 and F= (C*1.8)+32 . Try and find the radius of
14 a circle with a circumferance of 23 feet.
15
Screen 47 not modified
0 ( problem room.... bdk011987)
1
2 What is the area of circle 12.5 feet in diameter?
3
4
5
6
7
8
9
10
11
12
13
14
15 ( $$ )
Screen 48 not modified
0 ( chapter 6 glossary of loop words bdk012887)
1 GLOSSARY CHAPTER 6 ( LOOPS )
2
3 DO ... LOOP DO: (limit start -- ) LOOP: ( -- ) This word
4 sets up a finite loop, with a starting value and
5 a ending or limit value ( loop does no action
6 accept return to begining of DO).
7 DO ... +LOOP DO: (limit start -- ) +LOOP: (n -- ) Same as
8 plain loop, but adds n to value each time it loops.
9 LEAVE ( - ) Terminates loop at next LOOP or +LOOP.
10 BEGIN .. UNTIL UNTIL: (f - ) Loops until f becomes true.
11 BEGIN xxx WHILE yyy REPEAT WHILE: (f - ) Loop doing xxx
12 while yyy remainds true, leave when f is false.
13 .R (n width -- ) Prints unsigned value right justified
14 within specified field width.
15 PAGE ( - ) Send a form feed to the terminal or printer
Screen 49 not modified
0 ( chapter 6 glos and terms..loops... bdk011487)
1 QUIT ( - ) Kills current execution and returns to terminal.
2
3 CHAPTER 6 TERMS ( LOOPS )
4
5 DEFINITE LOOP A looping routine which will execute as many
6 times as needed to reach a fixed value after starting
7 from some preset value.
8 INFINITE LOOP More often called a LOCKED UP COMPUTER, one that
9 will never reach a determined value.
10 INDEFINITE LOOP Not to be confused with a infinite loop, this
11 loop ends when some predetermined value is reached.
12 Changes in flags or values will end these loops. This
13 loop starts with BEGIN, while definite loops use DO.
14
15
Screen 50 not modified
0 ( chapter 6 text on loops..... bdk011487)
1 CHAPTER 6 LOOPS
2
3 Loops are an extension of branching, it's just that they will
4 branch back to the begining of the word DO or BEGIN. A DO loop
5 takes values off the stack, the starting value on top and the
6 ending value below. The staring value is increased by one each
7 time through the loop until it equals the ending value. The
8 operations contained within the DO and LOOP are performed until
9 the items are equal. These items are not kept on the data stack
10 but stored on the return stack, which you can copy and print by
11 using the word I (see last chapter for more info). This value
12 is called the index and can be used within the loop to create
13 new values or pointers.
14 +LOOP takes the value off the stack and increments the loop
15 counter by this amount. +LOOPs can then count by steps to the
Screen 51 not modified
0 ( chapter 6 loops and more loops... bdk012887)
1 limit value, which is the second value on the return stack (use
2 I' to copy to data stack). Be careful of using 0 in loops,
3 becuse you could end up multiplying by 0 and never reach your
4 ending value, this is an infinite loops, never ends.
5 The other form of looping is the indefinite loop which
6 starts with BEGIN and ends with UNTIL. This loop will repeat
7 what is between the BEGIN and UNTIL, as long as the flag remains
8 true. This means you must perform some test within the loop
9 that will change the flag. A modified version of this loop is
10 BEGIN WHILE REPEAT loop. This loop works just the opposite of
11 the BEGIN UNTIL loop, it works only while the flag is true.
12 When the flag goes false this loop ends.
13 A regular DO LOOP can be ended early by LEAVEing it. Using
14 LEAVE within the loop will terminate the loop, so to prevent an
15 unwanted leave, enclose the term LEAVE within an IF THEN
Screen 52 not modified
0 ( chapter 6 last page of loops.. bdk012887)
1 statement. The IF is checked and as long as the condition is not
2 true, the loop will not be terminated by LEAVE but continue on
3 with THEN.
4 The text has several good examples of DO LOOPs and how to
5 use them. The text omits any BEGIN UNTIL loop problems, so lets
6 see if we can create a word using this loop. If printing stars
7 on the screen remember to clear it first with PAGE. Now lets
8 see if you can create a christmas tree using stars when the
9 stack contains the height or width as a value.
10 Should you want to see a sample of printing a tree with
11 the lowest branch value used as width, displayed at begining,
12 then enter 25 TREE for a tree with 25 stars accross the bottom.
13 If you want you can try and make the value enterd equal the
14 number of branches ( not stars ) by editing screen 53. Try it
15 first before looking at screen 53, it is more fun..... $$
Screen 53 not modified
0 ( tree width begin until bdk012887)
1
2 : STAR 42 EMIT ; ( print star )
3 : STARS 0 DO STAR LOOP ; ( print many stars )
4
5 : TREE ( n -- ) ( expects width to be on top of stack )
6 2/ 2* 1 + ( guarantee it is odd )
7 PAGE CR CR ( clear screen and move down )
8 1 39 DUP SPACES STAR ( get set and do a star )
9 BEGIN CR 1 - DUP SPACES ( start and move across )
10 SWAP 2 + DUP STARS ( set star count do it )
11 ROT SWAP >R DUP R> SWAP >R DUP >R ROT
12 R> R> = UNTIL ( shuffle and check star to count )
13 CR 39 SPACES STAR CR 39 SPACES STAR CR CR ;
14 ( the last line draws the tree stock and moves ok down )
15 ( $$ )
Screen 54 not modified
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Screen 55 not modified
0 ( chapter 7 glossary ..numbers bdk011987)
1 CHAPTER 7 GLOSSARY ( NUMBERS )
2
3 ASCII ( - c) Translate character into ASCII equivalent
4 U. (u - ) Prints unsigned number and one space
5 U.R (u wdth -) Display right justified unsigned number
6 U< (u1 u2 - f) Flag true if u1 < u2, single length unsigned
7 HEX ( - ) Set number base to sixteen
8 OCTAL ( - ) Set number base to eight ( not on all systems )
9 DECIMAL ( - ) Set number base to ten
10 <# Begins number conversion, unsigned double length
11 # Converts digit to output character string
12 #S Convert number until result is zero
13 c HOLD Insert an ASCII character in string at HOLD point
14 n SIGN Inserts minus if n is negative in string
15 #> Leaves number string and stack ready for TYPE
Screen 56 not modified
0 ( more number glossary chpt 7 bdk011987)
1 D+ (d1 d2 - d-sum) Adds two 32 bit numbers
2 D- (d1 d2 - d-diff) Subtract two 32 bit numbers
3 DNEGATE (d - -d) Change sign of 32 bit number
4 DABS (d - |d|) Returns absolute 32 bit value
5 DMAX (d1 d2 - dmax) Returns maximum of two 32 bit numbers
6 DMIN (d1 d2 - dmin) Returns minimum of two 32 bit numbers
7 D= (d1 d2 - f) Flags true if d1 and d2 are equal
8 D0= (d - f) Flag true if d equal zero
9 D< (d1 d2 - f) Flag true if d1 less than d2
10 DU< (ud1 ud2 - f) Flag true if unsigned d1 < unsigned d2
11 D. ( d - ) Prints signed 32 bit number
12 D.R ( d width - ) Prints signed 32 bit right justified
13 UM* (u1 u2 - ud) Multiply two 16 bit, gets 32 bit unsigned
14 UM/MOD (ud u1-u2 u3) Divides 32b by 16b, gets 16b rem and quot.
15 M* (n1 n2 -d-prod) Multiplies two 16b gets 32 bit result
Screen 57 not modified
0 ( last of glossary chapter 7 numbers... bdk011987)
1 M+ (d n - d-sum) Adds a 32b to 16b, returns 32bit number
2 M/ (d n - n-quot) Divides 32b by 16b, get 16b signed results
3 M*/ (d n u - d ) Multiplies then divides 32 by 16 get 32 bit
4
5
6 CHAPTER 7 TERMS ( NUMBERS )
7
8 ARITHMETIC SHIFTS Process of moving bit left or right, which
9 is same as multiplying or dividing by two.
10 ASCII The standard system of representing characters with
11 numbers, eight bits in length.
12 BINARY Number base of two, either on or off
13 BYTE Term for 8 bit value
14 CELL A Forth term for 16 bit value
15 DECIMAL The number base of 10
Screen 58 not modified
0 ( chpt 7 more terms.... bdk012887)
1 HEXADECIMAL Number base of 16
2 LITERAL A number that appears inside a definition
3 MASK A means of filtering out unwanted bits
4 NUMBER FORMATTING Changing binary number to display characters
5 OCTAL Number base of 8
6 SIGN BIT A bit used to indicate sign in signed numbers
7 TWO'S COMPLIMENT The binary method used to add negative values
8 UNSIGNED NUMBER A positive number
9 UNSIGNED SINGLE LENGTH NUMBER An interger between 0 and 65535
10 WORD In Forth the defined dictionary entry that will
11 perform some function or command
12
13
14
15
Screen 59 not modified
0 ( chapter 7 text.. numbers.. bdk012887)
1 CHAPTER 7 NUMBERS
2
3 Computers have only one way to handle numbers, that is the
4 BINARY method. Everything inside computers is either a one or
5 zero, a on or off, or combinations of these two states. Binary
6 is the term for this type of handling data. Humans however have
7 considerable trouble understanding these on and offs values, so
8 we have created number systems for the different ways we want to
9 represent data.
10 In a previous screen I indicated that ASCII characters is
11 what a computer uses to display information. A number has been
12 asigned for each character we wish to display. These and any
13 number can be represented in a binary form. To send a carriage
14 return to your screen we send a value of 13 decimal. The binary
15 representation of 13 is 00001101 and is what the computer
Screen 60 not modified
0 ( chapter 7 numbers more text... bdk012887)
1 actually sent to the display. Several shorthand methods are used
2 to indicate binary values. Some older computers use OCTAL or
3 base 8. Most new machines use HEXADECIMAL or base 16. Four bits
4 of binary 1 or 0s is used to get the hexadecimal value. Four HEX
5 (short for hexadeciaml) values will represent the sixteen bits
6 used in most of Forths single numbers. Double numbers are based
7 on using 32 bits or eight hex values. Remember the hex values
8 are just easy ways to express the 4 places of on and off data.
9 In forth we use normally 16 bits to represent an unsigned
10 number, 15 bits for a signed number with the 16th bit being the
11 sign. When counting in binary that is 65535 for unsigned and a
12 range of +32768 to - 32767 for signed numbers, all 16 bits. For
13 binary arithmetic check the book, it has some good samples
14 There are a number of Forth words which binary understanding
15 helps in knowing what they do. ASCII numbers are used by the
Screen 61 not modified
0 ( more chapter 7 text..numbers bdk012987)
1 EMIT word. This command emits an number to the display system.
2 F83 can take a character and automatically convert it to a ASCII
3 value. Using ASCII * EMIT will send a star to the display. The
4 same technique is used when changing base number systems. HEX
5 0A 12 + . will produce 1C as the answer. To get a decimal value
6 do HEX 0A 12 + DECIMAL . and it will print 28.
7 There are many ways to display numbers in Forth. To print
8 unsigned (16bit) numbers U. will print what is on the stack plus
9 a space after it. If you want numbers in a column use U.R where
10 stack top has the width of the column, and the second down has
11 the number that will be right justified. For DO LOOP compares on
12 unsigned numbers use U< to flag true if U1 is less than U2. We
13 can do the same functions with double length numbers (32bits).
14 D. prints signed numbers, UD. prints unsigned numbers, D.R like
15 U.R for signed 32 bit numbers, and DU< is 32 bit U<.
Screen 62 not modified
0 ( chapter 7 number formatting... bdk012187)
1 To display numbers it is necessary to format their output.
2 This formatting inserts . or / to indicate money or dates. The
3 method in Forth is to asign positions in a string, relative to
4 digits in the number being printed. The format words are <# # #>
5 and HOLD TYPE #S ASCII all can be used within the string. To
6 start a layout use <# then number of numbers used, your period
7 as a number (45) HOLD to hold a place by inserting a . there
8 and then #S to fill in any remainding numbers. The real problem
9 is the left most #, will be the right most number, or if we have
10 4 #s before the hold, it will have four values after the HOLD.
11 We also need to end the string with a #>, followed by TYPE which
12 will display the formatted number. No space is printed after
13 TYPE so you may need to follow it with a SPACE or n SPACES. You
14 should try some of the samples in the book to get a better
15 grasp of number formatting.
Screen 63 not modified
0 ( chapter 7 double and mixed numbers bdk012887)
1 There are a few double length operators that help handle
2 relationship between numbers. These are, DNEGATE which changes
3 the sign of a 32 bit number, DABS that returns the absolute
4 value, DMAX and DMIN for minimum and maximum of two numbers, D=
5 set flag true if two doublelength numbers ar equal, D0= if the
6 number is zero, D< true if d1 is less than d2. Remember these
7 operate the same as their single length number, but work on 32
8 bits of data, not 16.
9 As with single length number, some operations will require
10 intermediate answers that are longer than 32 bits. In */ the
11 16 bit values used a 32 bit intermediate value to maintain the
12 accuracy. M*/ takes a 32 bit number and multiplies it by a 16
13 bit getting a triple length results (48 bits), and then dividing
14 by a 16 bit number, return the answer as a 32 bit value.
15 There are several other MIXED LENGTH OPERATORS, they are UM*
Screen 64 not modified
0 ( last of chapter 7, mixed..definitions.. bdk012187)
1 mulitplies two 16 bits for a 32 bit answer, UM/MOD divides a 32
2 bit by a 16 bit, getting 16 bit answers all unsigned, M* takes
3 two 16 bits and multiplies for a signed 32 bit value, M+ adds a
4 32 and a 16 bit number for a 32 bit answer, M/ a 32 by 16 for a
5 16 bit answer.
6 One must remember that the number base you are in is used when
7 compiling a word. Inserting a HEX will not have the values in
8 the word compiled as hex values if you are in decimal at the
9 time. When words are executed, if they contain a number base,
10 the base will change at that time and interpret the numbers that
11 were stored literally into the equivalent base value.
12 The book has more details and some interesting problems. A
13 good problem is creating a BIT mask using a DO LOOP. A good and
14 useful word would be one that display bit patterns for values
15 entered, in both 16 and 32 bit lengths.
Screen 65 not modified
0 ( chapter 7 problem area and expansion... bdk012187)
1 Try some large size math problems using the new words from
2 this chapter.
3
4
5
6
7
8
9
10
11
12
13
14
15 ( $$ )
Screen 66 not modified
0 ( chapter 8 glossary for variables... bdk012187)
1 CHAPTER 8 GLOSSARY ( VARIABLES )
2
3 CONSTANT xxx ( n -) Creates a constant xxx with a value of n
4 VARIABLE xxx ( - ) Creates a variable xxx, xxx gets address
5 CREATE xxx ( - ) Creates dictionary header xxx
6 ! ( n a -) Stores single length number into address
7 @ ( a - n) Fetches contents of address to stack
8 ? ( a - ) Prints contents of address and a space
9 +! (n a - ) Adds n to contents of address (single length)
10 ALLOT ( n - ) Adds n bytes to the PFA of recently defined word
11 , ( n - ) Compiles n into next available cell in dict.
12 C, ( b - ) Compiles b ( byte) into available cell of dict.
13 C! (b a - ) Store a 8 bit value into address
14 C@ ( a - b) Fetch an 8 bit value ( byte) from address
15 FILL (a u b -) Fill memory u bytes long, starting a, with b
Screen 67 not modified
0 ( chapter 8 more glossary..variables... bdk012187)
1 ERASE (a u -) Stores u zeros starting at address a
2 BASE ( - a) Variable containing value of number base
3 DUMP (a u - ) Display u bytes of memory from a address
4 2VARIABLE xxx Creates double length variable
5 @CONSTANT xxx Creates double length constant
6 2! ( d a - ) Stores double length number into a address
7 2@ ( a - d ) Fetches double length double from a address
8 0. ( - 0 0 ) Puts a double length zero on stack
9 FALSE ( - 0 ) Returns a zero or false condition
10 TRUE ( - -1) Returns a -1 or all 16 bits set to one
11
12
13
14 CHAPTER 8 TERMS ( VARIABLES )
15
Screen 68 not modified
0 ( chapter 8 terms.. variables .. bdk012787)
1 ARRAY A series of memory locations referenced by one name
2 CONSTANT A fixed value referenced by a single name
3 FACTORING Pulling out common steps of a program into own words
4 FETCH To retrieve a value from a memory location
5 INDEX A number indicating a location within an array
6 INITIALIZE The setting of an array to known values
7 OFFSET An value added to address, pointing into an array
8 STORE Placing a value into memory location
9 VARIABLE Memory location for storing changing values
10
11
12
13
14 CHAPTER 8 VARIABLES AND ARRAYS
15
Screen 69 not modified
0 ( CHAPTER 8 TEXT .. VARIABLES bdk012187)
1 Most programs, including tutor.blk, need to use variables
2 and constants. Variables are pointers, temporary sums, or any
3 values that can be changed. Constants are values that are used
4 by programs and generally are not changed. Forth requires these
5 locations to be declared before use, using either VARIABLE or
6 CONSTANT inplace of the : . This tells the compiler to define a
7 word and allocate memory for it. Constants take a value off the
8 stack and place it in the allocated memory location. When these
9 words are used they return their address to the stack for use
10 by ! @ ? or +! .
11 ! means to store a value in location of address on stack with
12 value below it. @ gets or fetches value from address on stack.
13 ? is a combination of @ and . to get and print a value. +! adds
14 the number below the address on the stack, to the location of
15 address.
Screen 70 not modified
0 ( chapter 8 variable doubled..arrays..text bdk012187)
1 There are double words for variables: 2VARIABLE, constants:
2 2CONSTANT, as well as 2! to store a double length variable, and
3 2@ to fetch double length variables or constants.
4 Many programs use arrays, or a number of memory locations
5 that can contain values. Arrays can have fixed values, as in a
6 table of phone numbers, or variables which can keep count of a
7 number of events. To create an array in Forth use the word
8 CREATE and the name assigned to it. The compiler will set as
9 many memory locations aside as you ALLOT to it. An array of two
10 will be defined, unless you allot more. Placing values in or out
11 of an array is the same as any variable, it is just the address
12 provided will be for the first entry in the array. If you want
13 the seventh item, you must increment the address by 14 as each
14 location is 2 addresses in length. The same is true for ALLOT
15 you must double the value (10 ALLOT creates 5 16bit locations).
Screen 71 not modified
0 ( chapter 8 arrays and bytes.... bdk012187)
1 An example of an array is your programs memory. Forth has a
2 word for looking at this large array, it is DUMP. Place the
3 starting address on the stack, next push the count or how far
4 you want displayed, then DUMP and watch what is there.
5 As we said before a byte is 8 bits and is the smallest way
6 some machines handle information. You can get data from or into
7 an array in 8 bits at a time. Arrays of characters are all 8 bit
8 entries. C! stores 8 bits, while C@ fetch 8 bits, just remember
9 to set the address one step for each location in the array.
10 The , is used to create a constant with values entered at
11 time of compilation. Use values and a , for each entry instead
12 allotting space (do not forget the last , ).
13 Variables, constants, and arrays are easy to create in Forth
14 and just as easy to use. For a problem we can use the topic of
15 last chapter and this to create a telephone listing or array.
Screen 72 not modified
0 ( chapter 8 problems..telco array bdk012187)
1 This array should contain numbers and when queried with an
2 index produce formatted output. Lets give it a try...
3
4
5
6
7
8
9
10
11
12
13
14
15 ( $$ )
Screen 73 not modified
0 ( chapter 9..glossary and engines.... bdk012287)
1 CHAPTER 9 GLOSSARY ( FORTH ENGINE )
2
3 ' xxx ( - a ) Returns dictionary address of xxx
4 ['] ( - a ) Generates literal number used inside the words
5 definition of the next word used in definition
6 EXECUTE (a -) Executes the dictionary entry at address a
7 @EXECUTE (a -) Executes entry pointed to at address a
8 >BODY (cfa -pfa) Returns parameter field from compilation addr
9 EXIT ( -- ) Terminates or returns from definition
10 QUIT ( -- ) Clears stack, gets control, no ok prompt
11 ABORT ( -- ) Clears data stack then does QUIT
12 DP ( - a) Returns address of dictionary pointer
13 HERE ( -- a) Next available dictionary location
14 PAD ( -- a) Beginning address of character string buffer
15 SP@ ( -- a) Pointer to top of data stack
Screen 74 not modified
0 ( chapter 9 glossary of engine... bdk012187)
1 S0 ( -- a) Returns address of bottom of data stack
2 TIB ( -- a) Returns address of text input buffer
3 FORTH ( -- ) Makes FORTH context vocabulary
4 EDITOR ( -- ) Makes EDITOR context vocabulary
5 CONTEXT ( - a) Returns address of search order variable
6 CURRENT ( - a) Returns address of new word vocabulary ( vocs)
7 DEFINITIONS Sets the current vocs to context vocs
8
9
10
11
12 CHAPTER 9 TERMS ( FORTH ENGINE )
13
14 ADDRESS INTERPRETER Interprets the address from the colon
15 definitions and executes them
Screen 75 not modified
0 ( chapter 9 terms engines... bdk012187)
1 BODY The code and parameter of a dictionary entry
2 BOOT The basic starting portion of Forth, precompiled Forth
3 CFA Address of code field in a dictionary entry
4 CONTROL TASK A task that does not converse with Forth
5 CODE POINTER FIELD The entry in the dictionary that points to
6 the run time code
7 DEFINING WORD A Forth word that creates a dictionary entry
8 ELECTIVES Optional blocks of words like floating point math
9 FORWARD REFERENCE Refering to undefined words
10 HEAD Name and link field of dictionary entry
11 LINK FIELD Pointer to next entry of vocabulary, search order
12 NAME FIELD Location of name of word, includes word length
13 PAD Area of memory for intermediate data storage
14 PARAMETER FIELD The area of the definition in which the
15 actual code or values are contained
Screen 76 not modified
0 ( chapter 9 terms...forth engine... bdk012187)
1 PFA The address of the first entry of parmeter field
2 PRECOMPILED PORTION The Forth system loaded at boot time with
3 all dictionary words and terms ready to use
4 RUN-TIME CODE Usually the actual code that is the word
5 SYSTEM VARIABLES Variables usuable by all users in system
6 TASK A area of memory set aside for a given activity
7 TERMINAL TASK A task that has a user talking to Forth
8 TEXT INPUT BUFFER Memory area containing terminal input data
9 USER VARIABLE Variable accessible by one user only
10 VECTORED EXECUTION Executing words by going to a pointer
11 VOCABULARY An independent linked list of words. In F83
12 SHADOW EDITOR HIDDEN BUG ROOT USER ASSEMBLER
13 DOS FORTH are vocabularies. Use VOCS to see
14 this list of vocabularies.
15
Screen 77 not modified
0 ( chapter 9 forth engines text... bdk012187)
1
2 CHAPTER 9 FORTH ENGINE
3
4 Forth is a THREADED programing language. This means that a
5 action amounts to performing one instruction contained within
6 an instruction. Words which perform the actions are made up of
7 lists of addresses of words that together will perform the
8 desired action. These words within words can also have words
9 within them. If you follow the actual actions it is like a
10 thread linking all the actions together.
11 In comparing Forth to assembly language it would be like a
12 routine calling a subroutine which calls a subroutine and can
13 call more till it finally does something and then returns back
14 through each of the called routines. That final actual code
15 performing actions makes up the KERNAL of the system.
Screen 78 not modified
0 ( chapter 9 forth engine text..... bdk012787)
1 The kernal is written in native code of the machine it is
2 on. The kernal creates the stack and basic operations of Forth.
3 Utilities are then written using Forth words, building blocks
4 until a full system is created. To move the system to another
5 type of processor requires rewritting only the native code of
6 the inner most kernal, not the utilities.
7 Most computers are made up of CPU or central processor units
8 which have a number of registers and instructions to move data
9 between registers and the outside world. What Forth does is to
10 create an artificial processor in software that can be moved
11 to different machines. This created processor can give the user
12 near assembly language performance, while being transportable.
13 In F83 we have the normal kernal using the Forth-83 word set
14 as well as many utilities, which create a full system. All these
15 abilities are contained in the dictionary. When Forth words are
Screen 79 not modified
0 ( chapter 9 forth engine..... bdk012787)
1 interpreted, FIND searches the dictionary for a match, and then
2 EXECUTES the instructions. What is passed is not actual words
3 but their address. An word contains addresses or machine code.
4 The kernal items are mostly code, while utilities are mostly
5 addresses pointing to code containing words.
6 Forth has several ways to handle words by the user, one way
7 is ' which returns the address of the word, use U. to see the
8 actual address of a word ( ' SEE U. ). What interpret does is '
9 the word then does EXECUTE on the address on the stack. This is
10 not the address of the first address of a dictionary entry, but
11 the third. Lets look at how words are arranged.
12 When you create or define a word, several entries in memory
13 are completed. The word name is stored, up to 32 characters in
14 F83, after a count of the length of the name. Next is the link
15 to the next item in the current vocabulary. This link tells the
Screen 80 not modified
0 ( chapter 9 forth engine..... bdk012787)
1 interpreter where next to look if the current word is not a
2 match. After the link is the CODE FIELD ADDRESS or CFA. This is
3 what is returned by ' and points to the code or code intrepter.
4 The interpreter can be one of three types, variable, constant or
5 code. The variable and constant return address or values on to
6 the stack respectively. The code points to either actual machine
7 code if it is a kernal item, or more CFA's. What it points to is
8 called PARAMETER FIELD or PFA, and given the CFA >BODY will put
9 the PFA on the stack.
10 There are other actions that occur while the interpreter is
11 going through the PFA, mainly pushing the next PFA onto the
12 return stack. This is why use of the return stack must be done
13 within the : definition, not doing so destroys the pointer to
14 the next word. You can carefully handle this stack and cause
15 wanted results by dropping off pointers, use caution though!
Screen 81 not modified
0 ( chapter 9 engine exiting and map... bdk012787)
1 You can officially leave a diffinition, using QUIT ABORT or
2 ABORT" any of these three end the operation. Generally these
3 ways are used inside of IF THEN or DO LOOPs checking for flags
4 or problems. When the last PFA is found the word EXIT is left.
5 This word removes the pointer from the return stack and this is
6 interpreted next. EXIT can not be used inside of DO LOOP as it
7 will return loop counters and not addresses.
8 There are some ideas and words that you should know which
9 relate to the memory map of a Forth system. Normally from low
10 memory up is the kernal, system variables, utilities, users
11 dictionary space, the PAD, DATA STACK, TIB, RETURN STACK, users
12 variables, and block buffers. The users dictionary grows toward
13 the PAD, while the DATA and RETURN stacks grow down toward low
14 memory. The stack is actually a pointer to memory locations and
15 is lowered each time an entry is made.
Screen 82 not modified
0 ( chapter 9 system words..the engine.. bdk012787)
1 To find these locations in memory, use DP to find the last
2 or highest memory location free for new dictionary word entries.
3 DP is the pointer while HERE will place the pointer value on the
4 stack ( same as DP @ ). To find the true location of the stack
5 use SP@ and it will fetch the pointers value, while S0 will get
6 the starting address of the stack. In higher memory above the
7 data stack is the TIB or Text Input Buffer and it grows up
8 toward higher memory. TIB fetches the starting address of the
9 buffer. The input line interpreter reads this buffer to find out
10 what you have entered.
11 To improve speed of interpretation, the dictionary is sorted
12 into different lists or vocabularies. When in these vocabularies
13 Forth will only search those words through use of the linked
14 address value. Typing the name of a vocabulary puts you into
15 that linked list. These lists can be scanned consectatively if
Screen 83 not modified
0 ( chapter 9 last screen...vocs... bdk012287)
1 the word is not found in the first list. VOCS will display the
2 list of current vocabualries, while CONTXET shows the search
3 order. CURRENT will print which VOCS you are now in. To see the
4 words contained in one of these list, enter DOS WORDS and you
5 will see all the dictionary entries that relate to the DOS ( and
6 are used by Forth when talking to the operating system).
7 Take the time now and do some exploring in F83. Reading the
8 file README will explain some of the system terms and show a
9 memory map of a typical 8080 Forth system. Try reading all the
10 VOCS and check CONTEXT before and after changing vocabularies.
11
12
13
14
15 $$
Screen 84 not modified
0 ( chapter 10 glossary...I/O... bdk012787)
1 CHAPTER 10 GLOSSARY ( I/O )
2
3 UPDATE ( - ) Marks most recently used block as modified
4 SAVE-BUFFERS Writes all updated buffers to disk
5 FLUSH Does save-buffers then frees all buffers
6 EMPTY-BUFFERS Marks buffers as empty, all data is lost
7 BLOCK ( u - a) Put starting address of block u on stack
8 BUFFER ( u - a) Like block but does not load block from disk
9 TYPE ( a # -) Send # characters at addr a to output device
10 -TRAILING (a #1 - a #2) Changes byte count to reflect blanks
11 >TYPE ( a # -) TYPE for multiusers, puts string in PAD first
12 MOVE (a1 a2 # -) Moves # of cells from a1 to a2 (low > hi)
13 CMOVE (a1 a2 # -) Moves # of bytes from a1 to a2 (low > hi)
14 CMOVE> (a1 a2 #-) Moves # of bytes from a1 to a2 (hi > low)
15 BLANK ( a # -) Fill a with # of blank ASCII bytes
Screen 85 not modified
0 ( chapter 10 glossary I/O bdk012387)
1 KEY ( - c) Put next available INPUTED ASCII char on stack
2 EXPECT (a # -) Awaits # chars or CR from KEY storing at a
3 SPAN ( - a) Addrs of number of chars stored by EXPECT
4 WORD (c - a) Puts one word from input stream into addrs a
5 COUNT (a -a+1 #) Changes stack values of string a for TYPE
6 >IN ( - a ) Variable with pointer to next free input space
7 BLK ( - a ) Variable pointing to active block, 0= TIB
8 CONVERT (ud1 a1 -ud2 a2) Convert ASCII string a1 to binary ud2
9 NUMBER ( a -d ) Convert ASCII string a to binary values d
10 -TEXT (a1 # a2-f) Flag true if no match in strings # long
11 -MATCH (d # s # -a f) Find match in stings s/d return addrs flag
12 " ( - a ) Returns address of compiled string
13
14
15
Screen 86 not modified
0 ( chapter 10 terms ..I/O bdk012387)
1 CHAPTER 10 TERMS ( I/O )
2
3 EXPECTING Stop computing and wait for keyboard input
4 RELATIVE POINTER An index into an array used with address to
5 find true location of data
6 SCANNING Searching ahead for given characters
7 SUPERSTRING A string within an array of strings
8 VIRTUAL STRING Use of disk storage as if it were real memory
9
10
11
12
13
14
15
Screen 87 not modified
0 ( chapter 10 text of I/O.... bdk012787)
1 CHAPTER 10 I/O
2
3 Forth handles data in blocks or groups of data 1024 bytes
4 long. These can be in blocks of data on the disk or blocks of
5 data contained in buffers within Forths memory map. These blocks
6 can have data, screens of source code, text, or grabage. F83 has
7 a number of ways of handling these blocks of data.
8 When we list a screen, F83 checks to see if the block has
9 been load from disk, if not it loads it into a free buffer. Then
10 it returns a pointer to this block and LIST then displays it. If
11 we have edited a block or changed it, it will be UPDATEd and
12 marked for storage to disk. This storage is not done until the
13 buffer is needed. You can force the storage two ways. FLUSH will
14 empty all updated buffers and clear all pointers, while the word
15 SAVE-BUFFERS writes to disk, but does not clear the pointers.
Screen 88 not modified
0 ( chapter 10 I/O block and stuff.... bdk012787)
1 EMPTY-BUFFERS will clear all pointers without writting to
2 disk. Any data contained within the buffers is lost at the sake
3 of freeing all buffers for more data. Accessing these buffers
4 you use BLOCK to return the address of the first byte in the
5 numbered block. If the block is not already in memory, BLOCK
6 will force it to be read. BUFFER returns a blocks address but
7 will not force a read ( used within BLOCK).
8 We can get data into the system, either from the blocks or
9 from the input string (keyboard). As indicated before to output
10 characters to the terminal you use EMIT. To send strings you use
11 TYPE, with the count on top and string address below. TYPE will
12 print the characters including blanks, -TRAILING will return
13 without the blanks by changing the stack count, then use TYPE.
14 To get these strings into buffers or locations accessible to
15 our programs we can MOVE them around. MOVE copies 16 bit cells
Screen 89 not modified
0 ( chapter 10 I/O moves... bdk012787)
1 from locations pointed to by the third stack item to the second
2 stack address, and will move the count value(top stack). CMOVE
3 does the same, but count is now byte moves or 8 bits at a time.
4 These move the data from low memory to higher memory and could
5 over write data yet to be moved. CMOVE> starts from the top or
6 high memory and moves data down, preventing garbage generation.
7 Forth has several ways of getting input from the keyboard
8 into the system. KEY is the basic single character input word.
9 KEY? flags if the keyboard has been used. EXPECT will wait and
10 then store a string of characters from the keyboard.
11 Once we have the data in the TIB, we now need to be able to
12 process it. WORD will scan a string until it finds a given
13 character and then moves this string to a new buffer with the
14 count (length of string) as the first address. We use COUNT to
15 add one to the address and push the count on the stack.
Screen 90 not modified
0 ( chapter 10 I/O string working... bdk012787)
1 When performing your own control over Forth, you will want
2 more control than most programming languages provide. Many of
3 the string commands help you understand how Forth works, and
4 there are more pointers that may be of interest to you. >IN
5 tells where in the input string the interpreter is at, while BLK
6 indicates wether the system is taking input from the TIB or the
7 block buffers. If BLK is zero, input is from TIB, non zero is
8 block buffers.
9 There are two ways to compare strings looking for matches. The
10 -TEXT word compares two strings with a given length and will set
11 the flag false if they match. -MATCH searches for a match of one
12 string and its length within a second string of some length, if
13 a match is found the stack will contain the starting address of
14 the match and the flag set false (in that order).
15 The handling of strings is not difficult in Forth and in fact
Screen 91 not modified
0 ( chapter 10 last of I/O text... bdk012387)
1 you have more control over how to handle strings than any other
2 programming language. If Forth doesn't do what you want, just
3 write some word that does.
4 As a problem, try writing some words that find matches in
5 a block buffer and then change them to random words selected
6 from a second buffer, should be fun and produce some intersting
7 statements.
8
9
10
11
12
13
14
15 ( $$ )
Screen 92 not modified
0 ( chapter 11 extending....glossary bdk012787)
1 CHAPTER 11 GLOSSARY ( EXTENDING )
2
3 DOES> ( -- a) Separates compile data from run-time portion
4 IMMEDIATE To be executed not compiled into the word
5 COMPILE xxx Compile word xxx address into definition
6 LITERAL A value pushed on stack by a word (binary)
7 [ Leaves compile mode
8 ] Starts compile mode
9 [COMPILE] xxx Makes a immediate be treated as non-immediate
10 STATE ( -- a) True if compiling, false if interpreting
11 INTERPRET Perform text interpretation of input stream
12
13
14
15
Screen 93 not modified
0 ( chapter 11 extending..terms.. bdk012787)
1 CHAPTER 11 TERMS ( EXTENDING )
2
3 COMPILE-TIME The action of compiling or generating a new
4 dictionary entry, for later run-time use.
5 COMPILING WORD A word that has action only during the
6 compilation stage, to generate proper run-time action.
7 DEFINING WORD When executed defines a new dictionary entry
8 that may have compile-time and run-time parts.
9 IMMEDIATE WORD A word that gets executed during compilation
10 and not compiled into dictionary.
11 PRECEDENCE BIT The 16th bit, indicates wether a word should be
12 executed (immediadte) or compiled.
13 RUN-TIME The normal action which a word will take, which
14 is what the word DOES>, it's definition.
15
Screen 94 not modified
0 ( chapter 11 extending the dictionary..text.. bdk012787)
1 CHAPTER 11 EXTENDING
2
3 It is at this point that we find out how Forth works.
4 More important it is where we find out how to change Forth to
5 meet our needs. All of this is done by extending the dictionary
6 or when compared to other languages it would be like re-writting
7 the compiler so that it has new ways of handling the input. You
8 can never NOT do something in Forth, it may not at present have
9 a way of handling your desires, but learn its insides and you
10 can make it do anything.
11 We should remember that Forth has two states or actions
12 possible. The first is interpreting, the other compiling. In the
13 interpretive mode we take data from a source and perform actions
14 much like basic reads lines of code and acts on them. The other
15 mode creates new words for the interpreter to use. It would be
Screen 95 not modified
0 ( chapter 11 extending... bdk012787)
1 like creating a new print command in basic (something you can't
2 do).
3 The words we use in the interpret mode have all been defined
4 and compiled in the kernal of Forth. The UTILITY.BLK and CPU8088
5 .BLK have most of the source code words for you to look over. In
6 looking these words over we will see two possible actions that
7 can take place in creating the dictionary words. These two are
8 compile-time and run-time activities. .
9 When compiling if we used Forth words that act on the
10 input data immediately, we would get garbage. That is it would
11 output data as the word was being created, not when we are
12 invoking it. Therefore we need to have words that control when
13 words do their thing.
14 CREATE is the word that creates the dicitonary entry and
15 puts in link and code addresses. This word is used to define
Screen 96 not modified
0 ( chapter 11 extending.. bdk012787)
1 words like CONSTANT and VARIABLE. These words when we use them
2 will CREATE a dictionary input using the name we pass at that
3 time. CREATE doesn't do anything at the time it is used in the
4 defined word, only when we invoke it as part of a new defined
5 word. Now if we want the new defined word that was created by
6 using a word with CREATE in it, we use DOES>. DOES> separates
7 the creation from the activity when it is invoked. This is the
8 difference between compile-time and run-time actions.
9 Compile-time actions occur when the word is being created,
10 while run-time actions occur when the word is being interpreted.
11 It is important to understand the two different states of Forth
12 activities. You compile words into the dictionary which when
13 they get invoked will perform certain activities. To compile
14 these words may require some actions which are different from
15 the actions that occur at run-time (interpretation).
Screen 97 not modified
0 ( chapter 11 extending.. bdk012787)
1 Interpretation occurs at all times, it just that some of the
2 interpreting is used to make new dictionary entries and some is
3 used to handle screen output. You don't want the two actions to
4 become confussed.
5 F83 has defined two words which can help show the difference
6 between these two states ." and .( The ." will store a string
7 that is printed when the word is invoke as in error messages.
8 The .( will print the string only while the word is being
9 compiled, or as I have used in the load screen to TUTOR it tells
10 you to wait while it is loading new words.
11 If we want to compute some values that later will be part of
12 the new defined word as LITERAL values we would use [ and ] .
13 The [ means interpret now, while ] means to stop interpreting
14 and resume compiling the word. If you are compiling directly
15 from the keyboard ] will continue compilation after a carriage
Screen 98 not modified
0 ( chapter 11 extending and last text screen bdk012787)
1 return.
2 The word IMMEDIATE means that this word is used within a
3 compilation to do its action immediately. The opposite of this
4 is [COMPILE] which delays compiling of the word till used in an
5 other words compilation.
6 Keeping track of when and what is being compiled and
7 interpreted takes some time and practice. Use the book for most
8 of this discussion. The samples and charts of when and how the
9 dictionary is changed is too complex for this simple tutorial.
10 To really understand Forth, you must use it and play with it
11 understanding how to adapt it to your style of programming. F83
12 and Forth together should be able to solve programming problems
13 with ease once you understand it.
14 ENJOY.
15 ( $$ )