Commodore Chained Programs
The "64 Paintbox Loader" on page 128 of the December 1984 issue of COMPUTE! is simple and clean, but it seems to be backwards. How does it work?
J. Quinn
This is an example of a chained program—a program which loads and runs another program. Chaining programs with Commodore BASIC isn't too difficult, but it does involve a few tricks.
When you use the LOAD command from direct mode, the loaded program goes into memory without running. But if you use the LOAD command inside a program, whatever BASIC program (if any) is in memory after the loading is complete will run automatically. If the loaded program was BASIC, then that new program will begin executing. However, if a machine language program was loaded (with a final, 1 added to the LOAD command), then the BASIC program which requested the LOAD will start again from the beginning. This explains the peculiar construction of the 64 Paintbox Loader.
Something unexpected would happen if you used a seemingly more logical construction like this:
10 LOAD "MLGAME",8, 1 20 SYS 49152
When this loader program runs, the machine language program MLGAME loads into its proper location, but then the computer tries to restart the BASIC program currently in memory, which is still the loader program. So it loads the MLGAME program again (and again and again and again). The loader program never reaches line 20.
Since the variables established by the running BASIC program are kept intact while the new program is loading (unless overwritten by the program being loaded), you can make a small change:
10 IF L = 0 THEN L = 1 : LOAD "MLGAME", 8, 1 20 SYS 49152
When the loader (or any other BASIC program) is first run, all variables are erased, so L equals 0 and the game is loaded. After the LOAD, the program starts again from the beginning, but with variable values retained, so this time L is 1 and the program skips to line 20, which activates the ML program.
It is also possible to load one BASIC program from another. With careful planning, you can even run programs that are too large to fit into memory by breaking them into smaller parts and loading each part from the preceding portion. Since BASIC programs always load into the beginning of memory, the second program will overwrite the first. Variables may be erased, depending on how long the programs are. If the original program is larger, all numeric variables will be available for use in the second program.
String variables are passed to the second program only if they are dynamic. (Dynamic strings are those that involve some type of operation beyond simple string definition.) To be sure they make it, add a null string to the end of each string variable. Instead of A$="HELLO", use A$="HELLO" + "" to force the computer to store the string in high memory.
If the second program is larger, all variables will be lost when it is called by the first, so you must always pay close attention to program length when chaining BASIC programs.