-
Notifications
You must be signed in to change notification settings - Fork 126
Sub routine
It is recommended to break a program into small sub routines. Sub routines can reduce duplicate and complicacy code. MY-BASIC supports both structured sub routine with CALL/DEF/ENDDEF
and instructional sub routine with GOSUB/RETURN
, but you cannot use them both in one program. It’s recommended to use structured CALL/DEF/ENDDEF
to write more elegant programs.
This document describes structured sub routine in MY-BASIC, read MY-BASIC Quick Reference for information about instructional sub routine.
A sub routine begins with a DEF
statement and ends with ENDDEF
, you can add any numbers of parameters to a sub routine. It’s quite similar to call a sub routine with calling a scripting interface, note you need to write an explicit CALL
statement, if you were calling a sub routine which was defined after the calling statement. A sub routine returns the value of the last expression back to its caller, or you may use an explicit RETURN
statement. See below for example:
a = 1
b = 0
def fun(d)
d = call bar(d)
sin(10)
return d ' try comment this line
enddef
def foo(b)
a = 2
return a + b
enddef
def bar(c)
return foo(c)
enddef
r = fun(2 * 5)
print r; a; b; c;
As you may see, a variable defined in a sub routine is only visible inside the local routine scope.
MY-BASIC supports recursive sub routines and tail recursion optimization.
- Principles
- Coding
- Data types
- Standalone shell
- Integration
- Customization
- More scripting API
- FAQ