A course for the Dragon 32 · Chapters 0 to 15
You are reading a book. Mum calls you: “Pop to the shop and get some bread.” What do you do with the book? You put a bookmark in the page, go, get the bread, come back, and carry on exactly where you stopped.
The processor can do this too. JSR tells it: “Go and do this job, and come back.” A piece of program that you go to and come back from is called a subroutine. At its end is written RTS: “Go back to the bookmark.”
You already know this! Since Chapter 2 you have been writing JSR ,X in the fixed ending. That is a jump to one of the Dragon’s subroutines, the keyboard checker, and it comes back from it with the answer. Now we will write subroutines of our own.
In this example there is a subroutine called DOT, which draws a red brick (two squares) at the place the finger Y points at. The main program calls it three times. Notice where DOT is written: after the fixed ending. The processor will never walk into it by itself, only through JSR.
The processor’s bookmark is a house number: the house of the line after the JSR. It writes it on a plate, and puts the plate on a pile. This pile is called the stack.
JSR plate takes up two houses (a house number is a big number). So JSR takes S down by 2, and RTS takes it up by 2. The pile grows downwards in memory.RTS: it takes DREAM’s plate, and goes back to it. The whole program is a subroutine too.A good subroutine does one job, and you can ask it for that job again and again, a little differently each time. SQUARE draws a 2 by 2 square. Before calling it, you put the “instructions” in the drawers: in Y where, in A which colour.
The main program writes letters: A, then B, then C... It keeps the letter in drawer A, and adds 1 on every lap (INCA). The subroutine UNDER draws a red line under each letter. But for that it needs A for the colour. What will happen to the letter?
The answer: before it touches A, it puts a copy of A on the pile of plates: PSHS A. At the end it takes it back: PULS A. That way the main program gets A back exactly as it left it.
PSHS = “put on the pile” (push). PULS = “take from the pile” (pull). You can put several drawers on at once, for example PSHS A,B. And remember: what goes on last comes off first.The same program, but someone forgot the PULS A. RTS doesn’t know what is on the plates. It simply takes two houses from the top, and trusts that this is the bookmark.
This is one of the most famous bugs in machine code. The rule: in every subroutine, as many plates as you put on, that many you take off, before the RTS.
A hobbyist tribute project, not affiliated with or endorsed by Dragon Data. The course, drawings and text are our own. Every program in the course was checked on the site's Dragon machine (XRoar running the BASIC we wrote).