|Powered by QM on a Linux server|
KnowledgeBase 00056: Local Subroutines and Functions
Historically, the multivalue Basic language has allowed internal subroutines entered using GOSUB but they are just a labelled part of the program in which they occur, with no ability for variables to have restricted scope or to make effective use of recursion.
QMBasic supports local subroutines and functions that may have private variables and can be called recursively. It is also possible to pass arguments to these routines.
A local subroutine is written within the body of the program just like a conventional internal subroutine but is introduced by a line
LOCAL SUBROUTINE nameand terminated by a corresponding END statement.
The LOCAL SUBROUTINE line may be followed by one or more lines declaring scalar or matrix variables that are private to the subroutine.
PRIVATE VAR1, VAR2, VAR3(10)If a variable of the same name exists elsewhere in the program, it will not be visible from inside the subroutine.
Private variables are not just standard variables that the compiler hides from other parts of the program. They are truly related to the local subroutine such that, if the subroutine is called recursively, each instance has its own versions of the private variables.
Local subroutines can also take arguments
LOCAL SUBROUTINE name(arg1, arg2)in which case the GOSUB statement is extended to become
GOSUB name(arg1, arg2)As with external subroutine declarations (the SUBROUTINE statement), an argument can be forced to be passed by value by enclosing its name in parentheses.
A local function is similar to a local subroutine but returns a value. It may be used in the same way as other functions. The function is introduced by a line of the form
LOCAL FUNCTION name(arg1, arg2)
Like other user written functions, a corresponding DEFFUN statement must appear in the program before first use of the function.
DEFFUN name(arg1, arg2) LOCAL
When using the QMBasic debugger, the names of private variables are formed from the local subroutine or function name and the private variable name with an intervening colon. For example, MYSUB:VAR1.