k10:k10.5:k10.5.7:start
Table of Contents
10.5.7 GoSub
The 'GoSub' statement exists in Gambas since version 3.1.
10.5.7.1 GoSub syntax
It is unconditionally changed to a label that is explained elsewhere in the function or procedure. If there is a return statement in the instructions under the target (-Label), the program returns to execute the code immediately after the GoSub statement.
GoSub Label * Instruction(s) -> program continuation after RETURN Label: Instruction(s) …
10.5.7.2 Notes on the syntax
- To return to * after the instructions under the target (-Label) label, you must use the Return statement on one line alone.
- However, you cannot use a return to leave a subroutine written between Label: and the GoSub-Return. A little nuisance - but not to change.
- GoSub calls can be nested.
10.5.7.3 Example 1
In chapter → 16.10 HistoryBox a TextBox is extended by the History property to temporarily store a certain number of entries.
In the following TextBox_KeyPress() procedure, for example, the same source code section of lines 17-19 is used two times in different places (lines 6 and 10):
[1] Public Sub TextBox_KeyPress() [2] [3] If Not $hHistory Then Return [4] Select Key.Code [5] Case Key.Up [6] GoSub UPDATE_HISTORY [7] Inc $iCurrent [8] Goto UPDATE_TEXTBOX [9] Case Key.Down [10] GoSub UPDATE_HISTORY [11] Dec $iCurrent [12] Goto UPDATE_TEXTBOX [13] End Select [14] Return [15] [16] UPDATE_HISTORY: [17] If $iCurrent = -1 Then Return [18] $hHistory[$iCurrent] = Super.Text [19] Raise HistoryChange [20] RETURN [21] [22] UPDATE_TEXTBOX: [23] If $iCurrent = -2 Then Inc $iCurrent [24] If $iCurrent = -1 Then [25] Super.Clear() [26] Return [27] Endif [28] If $iCurrent >= $hHistory.Size Then Dec $iCurrent [29] Super.Text = $hHistory[$iCurrent] [30] Return [31] [32] End
- The GoSub instructions in lines 6 and 10 are followed by unconditional jumps to the destination (-label) in line 16, and after the instructions in lines 17-19, return to lines 7 and 11 in line 20 with RETURN.
- The return in lines 3, 14, 17, 26 and 30 will cause the TextBox_KeyPress() procedure to quit!
Another example of how to use the GoSub statement is Tobias Boege's Pong project from the Gambas sample projects in the Games category.
Download
k10/k10.5/k10.5.7/start.txt · Last modified: by 127.0.0.1
