SmallBASIC GuideThe language | Programming Tips | Commands | System | Graphics & Sound | Miscellaneous | File system | Mathematics | 2D Algebra | Strings | Console | Glossary |
Subroutines and Functions
Syntax of procedure (SUB) statements
SUB name [([BYREF] par1 [, ...[BYREF] parN)]]
[LOCAL var[, var[, ...]]]
[EXIT SUB]
...
END
Syntax of function (FUNC) statements
FUNC name[([BYREF] par1 [, ...[BYREF] parN)]]
[LOCAL var[, var[, ...]]]
[EXIT FUNC]
...
name=return-value
END
On functions you must use the function's name to return the value.
That is, the function-name acts like a variable and it is the
function's returned value.
The parameters are 'by value' by default.
Passing parameters by value means the executor makes a copy of the
parameter to stack. The value in caller's code will not be changed.
Use BYREF keyword for passing parameters 'by reference'.
Passing parameters by reference means the executor push the pointer
of variable into the stack. The value in caller's code will be the
changed.
' Passing 'x' by value
SUB F(x)
x=1
END
x=2
F x
? x:REM displays 2
' Passing 'x' by reference
SUB F(BYREF x)
x=1
END
x=2
F x
? x:REM displays 1
You can use the symbol '@@' instead of BYREF.
There is no difference between @@ and BYREF.
SUB F(@@x)
x=1
END
On a multi-section (PalmOS) applications sub/funcs needs
declaration on the main section.
#sec:Main
declare func f(x)
#sec:another section
func f(x)
...
end
Use the LOCAL keyword for local variables.
LOCAL creates variables (dynamic) at routine's code.
SUB MYPROC
LOCAL N:REM LOCAL VAR
N=2
? N:REM displays 2
END
N=1:REM GLOBAL VAR
MYPROC
? N:REM displays 1
You can send arrays as parameters.
When using arrays as parameters its better to use them as BYREF;
otherwise their data will be duplicated in memory space.
SUB FBR(BYREF tbl)
? FRE(0)
...
END
SUB FBV(tbl)
? FRE(0)
...
END
' MAIN
DIM dt(128)
...
? FRE(0)
FBR dt
? FRE(0)
FBV dt
? FRE(0)
Passing & returning arrays, using local arrays.
func fill(a)
local b, i
dim b(16)
for i=0 to 16
b(i)=16-a(i)
next
fill=b
end
DIM v()
v=fill(v)
[Prev] [Next]