Page 43 of 62
SBasic User's Manual SBasic Version 2.7 Page 43
Printed: December 5, 1999
SBasic automatically pushes all arguments onto the data stack, then
calls the named subroutine as above. Code in the subroutine can use
the data stack operators, such as PICK(), to test or change the
arguments.
Pay careful attention to the order in which SBasic pushes the
arguments; they are pushed in the order given. For example:
gosub foo, 3, j
^ ^
| +--------- This argument is on top of data stack
+------------ This argument is next on data stack
This method of passing arguments means that a subroutine may be passed
different numbers of arguments at any time. SBasic performs no checks
to see if you have passed the correct number of arguments.
SBasic similarly does not "clean up" the data stack before returning
control to the calling routine. Your code must update the data stack,
if necessary, to remove any arguments. You can choose to do this
within the called routine, or in the calling routine after the
subroutine invocation. Regardless of where you perform this cleanup,
it must be done or your program will eventually corrupt the data
stack, likely crashing.
Note that GOSUBs make no allowance for the called routine returning a
value. Thus, code that uses a GOSUB to invoke a subroutine must rely
on global variables to check the results of the GOSUB. This can
result in awkward code that can prove difficult to maintain.
To return a value to the calling routine, use SBasic's USR() function.
The USR() function is similar to GOSUB, in that it calls an SBasic
subroutine. It can also include one or more arguments.
Unlike GOSUB, however, USR() returns a value from the called routine
for later use. For example:
n = usr(foo, 3) ' call FOO, put returned value in N
j = usr(bar) ' call BAR with no arguments
Note the difference between USR() and GOSUB. The USR() function, like
any other SBasic function, requires parentheses around its list of
arguments.
The address of the subroutine invoked must be either a label or a
variable; you may not use algebraic expressions or functions as
addresses for a USR() function.
USR() functions use the data stack in exactly the same manner
described above for the GOSUB statement. Also, the first argument in
the USR() list is always the address of the called subroutine.