If I am in a Forth environment, how do I leave, and how do I program a word to leave?
1 Answers
There are two ways to 'leave' Forth code, depending on what you need to do.
BYE
The Forth standard defines the word BYE
to leave the Forth environment itself.
BYE
( -- )
Return control to the host operating system, if any.
This word gets a lot of creative interpretations when your Forth is not running as a program in an operating system. For example, on some systems where Forth is the operating system, BYE
causes the system to restart instead, letting you load another OS.
BYE
is part of the Programming-Tools Extensions word set.
QUIT
There is a word in the Core word set called QUIT
, but it does not leave the environment. Instead, it leaves execution of a word and returns you back to the interpreter. This is why it is called 'QUIT', it is quitting in another sense.
QUIT
( -- ) ( R: i*x -- )
Empty the return stack, store zero inSOURCE-ID
if it is present, make user input device the input source, and enter interpretation state. Do not display a message. Repeat the following:
- Accept a line from the input source into the input buffer, set
>IN
to zero, and interpret.- Display the implementation-defined system prompt if in interpretation state, all processing has been completed, and no ambiguous condition exists.
Rather than defining QUIT
as something like "this word returns you to the interpreter", instead QUIT
is really defined as the interpreter itself in the Forth standard. In a factored Forth implementation, this makes sense: the word that puts you back in the interpreter and the interpreter itself can be the same word, they both can just clear the return stack and start interpreting.
And QUIT
is the word you are more likely to see used in colon definitions, because it is a convenient way to break out of a stack of word executions, leaving the current contents of the data stack as-is, and returning to the interpreter. You can, of course, use BYE
in a colon definition, for example in a custom interpreter or environment written in Forth to exit back to the operating system.