gosub and return - coldrockgames/doc-scriptor GitHub Wiki
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.
Syntax
Similar to the goto
command:
gosub jumplabel
continues_here_after_return
jumplabel:
//... some code
return
...but with a twist: return
may return a value, just like a function does!
$res
variable
The Due to the single line architecture of scriptor
, you can not do an assignment statement with a gosub
. Instead, the returned value of a gosub
can be retrieved through the scriptor variable $res
, which is created when you run a gosub
command:
gosub subroutine
result = $res
// "result" contains 6 now
subroutine:
return 4 + 2
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