On Gosub
Syntax
On Index Variable Gosub Label1 {,...Labeln }
Overview
Cause the program to Call a subroutine based on an index value. A subsequent Return will continue the program immediately following the On Gosub command.
Parameters
Index Variable is a constant, variable, or expression, that specifies the label to call. Label1...Labeln are valid labels that specify where to call.
Example
Device = 24HJ128GP502
' Select the device to compile for
Declare Xtal = 16
Dim Index as Byte
Cls
' Clear the LCD
While
' Create an infinite loop
For Index = 0 to 2
' Create a loop to call all the labels
' Call the label depending on the value of Index
On Index Gosub Label_0, Label_1, Label_2
DelayMs 500
' Wait 500ms after the subroutine has returned
Next
Wend
' Do it forever
Label_0:
Print At 1,1,"Label 0"
' Display the Label name on the LCD
Return
Label_1:
Print At 1,1,"Label 1"
' Display the Label name on the LCD
Return
Label_2:
Print At 1,1,"Label 2"
' Display the Label name on the LCD
Return
The above example, a loop is formed that will load the variable Index with values 0 to 2. The On Gosub command will then use that value to call each subroutine in turn. Each subroutine will Return to the DelayMs command, ready for the next scan of the loop.
Notes.
On Gosub is useful when you want to organise a structure such as: -
If Var1 = 0 Then Gosub Label_0 ' Var1 = 0: call label "Label_0"
If Var1 = 1 Then Gosub Label_1 ' Var1 = 1: call label "Label_1"
If Var1 = 2 Then Gosub Label_2 ' Var1 = 2: call label "Label_2"
You can use On Gosub to organise this into a single statement: -
On Var1 Gosub Label_0, Label_1, Label_2
This works exactly the same as the above If...Then example. If the value is not in range (in this case if Var1 is greater than 2), On Gosub does nothing. The program continues with the next instruction..