Performs a branch to a local subroutine specified after GoSub, depending on the value of the expression after On.
On n GoSub label1, label2, …
n:integer expression
label1,label2, …:label names
A branch to a local subroutine starting with a label is performed, depending on the value of n. If the value of n is less than 1 or greater than the number of labels specified after GoSub, no branch will be invoked. If n is not an integer, a Trunc(n) will be performed first and, if needed, a branch will then be taken. After a local subroutine invoked using On...GoSub is executed the program continues with the first statement after On...GoSub. If a local subroutine is not invoked, the execution immediately continues with the first statement after On...GoSub.
No parameters can be passed to a subroutine invoked with On...GoSub.
ColorPrint("Happy Birthday", 1)
ColorPrint("To Me", 2)
Procedure ColorPrint(a$, opt)
On opt GoSub pr, pr1
pr:
Color 0
Print a$
Return
pr1:
Color 255
Print a$
Return
EndProc
Only one On...Gosub statement can be used in any one procedure, function or sub-routine as that particular program section stops on returning from the statement called. This is shown in this alternative version of the above-listed On-Gosub example below:
Tron dbshow // Gives a record of program execution in the debug window
ColorPrint("Happy Birthday", 1, "To Me", 2)
Procedure ColorPrint(a$, opt, b$, opt2)
On opt GoSub pr, pr1
a$ = b$ : opt = opt2
On opt GoSub pr, pr1
pr:
Color 0
Print a$
Return
pr1:
Color 255
Print a$
Return
EndProc
Proc dbshow
Debug Trace$
EndProc
An alternative would be either to embed the On...Gosub command within a separate function (as is done in the original example) or to use Select...EndSelect (or Switch...EndSwitch) instead of the On part of the statement as shown below:
ColorPrint("Happy Birthday", 1, "To Me", 2)
Procedure ColorPrint(a$, opt, b$, opt2)
Select opt
Case 1 : GoSub pr
Case 2 : GoSub pr1
EndSelect
a$ = b$
Select opt2
Case 1 : GoSub pr
Case 2 : GoSub pr1
EndSelect
Return
pr:
Color 0
Print a$
Return
pr1:
Color 255
Print a$
Return
EndProc
On GoTo, On Call, GoTo, If, Select
{Created by Sjouke Hamstra; Last updated: 20/10/2014 by James Gaite}