More Ways to Control Program Flow
A Tiny BASIC program will finish when it has executed whatever is on the last line. But sometimes you might want it to end before that. Our box game from the previous section might be more profitable to us if it doesn't let the player keep choosing a box until they win. In that case, we'd want to replace lines 60 to 75 with the following:
60 PRINT "You win nothing." 65 END 70 PRINT "You win a wooden spoon." 75 END
These two lines ensure that the game is over if the player chooses one of the wrong boxes; it's no longer a certainty that they'll eventually find the gold. End isn't the last word in controlling program flow, though. In Tiny BASIC we also have subroutines.
Subroutines are a very powerful facility. They help you to better structure your program by splitting it into manageable tasks. They also save you from copying and pasting code if you perform a similar task in two or more different parts of your program. Subroutines in Tiny BASIC use the GOSUB and RETURN commands.
The GOSUB command is a bit like the GOTO command. It takes a line label, or an expression that results in a line label. It passes control to the statement on that line, just like GOTO. But unlike GOTO, it remembers where it came from, and that's where RETURN comes in. When a RETURN statement is encountered, control returns back to the statement following the GOSUB. It doesn't matter if there are multiple GOSUBs going to the same place; Tiny BASIC will remember which one it came from, and go back there when it arrives at a RETURN.
Here's part of a game which picks two cards, and displays their proper rank. Only one subroutine is needed to display a card's rank, but we call it twice, once for each card.
10 LET M=5 20 LET Y=12 30 PRINT "My card is:" 40 LET R=M 50 GOSUB 100 60 PRINT "Your card is:" 70 LET R=Y 80 GOSUB 100 90 END 100 IF R=1 THEN PRINT "Ace" 110 IF R>1 THEN IF R<11 THEN PRINT R 120 IF R=11 THEN PRINT "Jack" 130 IF R=12 THEN PRINT "Queen" 140 IF R=13 THEN PRINT "King" 150 RETURN
The subroutine begins at 100. It expects a variable R to be set to the rank of the card that will be displayed. See how we set this on lines 40 and 70 just before we call the subroutine with GOSUB. Another thing to note is the END on line 90. This stops the program before it can blunder into line 100 by accident. If Tiny BASIC enters a subroutine by means other than a GOSUB, an error will result when it reaches the RETURN.
Next: Final Remarks
Comments