18.9. GOSUB and RETURN

[<<<] [>>>]

Most basic language implementations contain the commands GOSUB and RETURN. ScriptBasic is no different. This command pair is the old form of subroutine calling that existed in the basic language before functions and subroutines were invented. When a GOSUB command is executed there is no new function or subroutine started with local variables and return value. This is almost the same as executing the command GOTO. You have to specify where the execution of the code is to be continued using a label and the execution will go on at that label. The only difference between GOTO and GOSUB is that GOTO forgets where it jumped to the specified label from. GOSUB on the other hand remembers and whenever a RETURN command is executed it jumps back to the command following the instruction GOSUB.

A code fragment started by a GOSUB command can use another GOSUB command any level deep and the command RETURN will always return to the command line following the last executed, matching GOSUB. For example:

print 1
gosub sub1
print 5
stop
sub1:
print 2
gosub sub2
print 4

return sub2: print 3 return

will print

12345

When a GOSUB command is executed inside a function or a "real" subroutine that starts with the command SUB the label following the keyword GOSUB can not be outside the actual function or subroutine. It is not a must to return from a code segment started with GOSUB. If there is a GOSUB in the program and the program finishes before reaching the pairing RETURN the program just finishes normally. This is not an error. Also when a function or sub finishes before executing a RETURN command for an already executed GOSUB in that function or sub the execution simply returns to the following command where the function or sub was called and the unpaired GOSUB return address or addresses are dropped. For example:

sub sub1
print 3
gosub kukk
print "never printed"
exit sub
kukk:
print 4
end sub

print 1

gosub obenal print 6 stop obenal: print 2 call sub1 print 5 return

will print

123456

[<<<] [>>>]