10.3 Vectored execution. 4tH 4tH Forth compiler
Reklama
Reklama
CHAPTER 10. INTEGER SEGMENT AND CODE SEGMENT
’ add constant add-address variable addr
’ add addr !
create addresses ’ add ,
120
Are you with us so far? If we would simply write "ADD", "ADD" would be executed right away and no value would be left on the stack. Tick forces 4tH to throw the address of
"ADD" on the stack instead of executing "ADD".
Note this only works for your own colon-definitions. It doesn’t work for 4tHs built-in words. If you try to, you’ll get an error-message. What you can actually do with it, we will show you in the next section.
10.3
Vectored execution
This is a thing that can be terribly difficult in other languages, but is extremely easy in
Forth. Maybe you’ve ever seen a BASIC program like this:
10 LET A=40
20 GOSUB A
30 END
40 PRINT "Hello"
50 RETURN
60 PRINT "Goodbye"
70 RETURN
If you execute this program, it will print "Hello". If you change variable "A" to "60", it will print "Goodbye". In fact, the mere expression "GOSUB A" can do two different things. In
4tH you can do this much more comfortable:
: goodbye ." Goodbye" cr ;
: hello ." Hello" cr ; variable a
: greet a @ execute ;
’ hello a !
greet
’ goodbye a !
greet
What are we doing here? First, we define a few colon-definitions, called "HELLO" and
"GOODBYE". Second, we define a variable called "A". Third, we define another colondefinition which fetches the value of "A" and executes it by calling ’EXECUTE’. Then, we get the address of "HELLO" (by using "’ HELLO") and assign it to "A" (by using "A !").
Finally, we execute "GREET" and it says "Hello".
It seems as if "GREET" is simply an alias for "HELLO", but if it were it would print
"Hello" throughout the program. However, the second time we execute "GREET", it prints
"Goodbye". That is because we assigned the address of "GOODBYE" to "A".
The trick behind this all is ’EXECUTE’. ’EXECUTE’ takes the address of e.g. "HELLO" from the stack and calls it. In fact, the expression:
Stiahnuť
Reklama