Level 3, lesson 3

# 3.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-definions, called "HELLO" and "GOODBYE". Second, we define a variable called "A". Third, we define another colon-definition 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:

         hello

Is equivalent to:

         ' hello execute

This can be extremely useful as we will see in the next chapter when we build a full-fledged interpreter. We'll give you a little hint:

         create subs ' hello , ' goodbye ,

Does this give you any ideas?