-
Notifications
You must be signed in to change notification settings - Fork 0
gosub and return
If you ever coded in old basic languages back in the 80's, you might know the gosub
command already. If not, here's what this does:
In contrast to a goto
, which simply jumps to a label and continues from there, a gosub
(read: "goto sub routine") also jumps, but it remembers, where it came from and when a return
statement is encountered, script execution jumps back to the line after the original gosub
.
This is a simple mechanism to create kind of sub routines, which do things, and then return and continue in the main path of the script.
Similar to the goto
command:
gosub jumplabel
continues_here_after_return
jumplabel:
//... some code
return
Here is an example, how it looks like in a real script, taken from one of the unit tests of scriptor:
test = 0
returned = 0
// now enter the sub routine, which sets "test" to 1
gosub add_it
// script continues here after the "return" in add_it
returned = 1
// skip/jump over the sub routine to the end of the script
goto end
add_it:
test++
return
never_reached = true
end:
returned++
The line never_reached
will never be reached, because return
leaves the path and jumps back, and the main path jumps over it to the end:
label.
At the end of the script, the variables have these values:
-
returned = 2
(Can you figure out/understand, why it is 2?) -
test = 1
(The subroutine was entered only once) -
never_reached
does not exist, as this line is never hit
Back to Repo ● Wiki Home
Copyright © coldrock.games