GOSUB
A much nicer way of branching your code out is using GOSUBs.
This statement is almost identical to GOTO, it allows you to go to a label anywhere in the program, except that
you can return from that part of the program with the keyword RETURN.
This allows you to branch to a different part of the program and return once you're finished there. Which sounds
unremarkable at first, but when there is a piece of code that you want to use repeatedly it comes in handy, because you only have to
type it in once.
The general form of the GOSUB is this:
GOSUB label
...
label:
'Code goes here
RETURN
Once again the label can be anything, including numbers, just like GOTO's. The label for a GOSUB can
be anywhere in the program, you just must to remember to close your block of code with a RETURN statement if you don't you will
get an error.
The RETURN will return the program back to the line after the GOSUB was called.
Example:
A% = 1
IF A% = 1 THEN GOSUB A1
END
A1:
PRINT "A% is equal to 1"
RETURN
Output:
A% is equal to 1
In this example A1 is called and then the program executes the code after A1, until it gets to RETURN
then the program goes back to the line after GOSUB was called, and the program ends. Notice that I put an END in
after the GOSUB A1, this is because if there was no END there the program would keep going through A1 and hit the return. This is a problem, because the
interpreter finds it and says, what? I didn't call any label. and then you
get an error like RETURN without GOSUB.
This is one of those things that you need to keep an eye on when creating programs, because until you get used to the error messages and what they mean
you will have a hard time figuring out what exactly is going on.