One of the issues of most of the information out there with respect to the forth language (and this includes books) is the lack of a clear illustration of how to write a routine and call it in the program in a easy to understand manner. They show how to write a routine and call it from another routine but no one tells you where your main program should be to call all the functions… do you create an main() like routine, do you put the instructions at the beginning and the routines after, or do you define the routines and call them after…. most of the forth manuals seem to skip this part in clear english. I am not a anything like an experienced forth programmer, but like all experimental programmers, I am interested in all programming languages, including forth… while most of what I might do is in other languages, I would like to say that I know something of forth, but most of the information out there leaves a lot to be desired when you do not “know” forth.
Anyway this is my illustration of routine calls in a forth program. Ye old “Hello World” program. I believe all first “Hello World” program in any programming language should illustrate how routines (subroutines or functions) call called.
: hello ." Hello World" cr ; hello bye
So what does this program do? First it defines a routine called “hello” that does only one thing, print the text string “Hello World” with a carriage return.
With respect to forth, the routine must be defined before being used, so it comes before any instruction that calls the routine. This is why the rest of the program follows the routine. BTW the routine definition is terminated by the semi-colon. (Note all colons and semi-colons are spaced away from any other element, as forth needs a space when parsing to determine it sytnax).
There is no main() like construct in forth, so the instructions are listed right after all routines are defined. We therefore have two instructions: “hello” and “bye”. “hello” calls the hello routine and executes it before passing it off to the next instruction “bye” which in gforth tells the forth environment to terminate, exiting the program.
There you have it, a gforth “hello world” program that illustrates the use of routines in the source program.