-
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