Skip to content

Sub routine

Wang Renxin edited this page Jul 9, 2022 · 20 revisions

The same logic can be reused with routines, and it makes complex program into simple pieces. MY-BASIC supports both structured routine with CALL/DEF/ENDDEF and instructional routine with GOSUB/RETURN, but you cannot use them together in one program.

This document describes structured routine in MY-BASIC, read MY-BASIC Quick Reference for information about instructional routine. For another topic about calling from BASIC to C and from C to BASIC, see another Callback page.

How to use

A routine begins with a DEF statement and ends with ENDDEF, you can add any numbers of parameters to a routine. It's quite similar to call a routine as calling a BASIC function, note you need to write an explicit CALL statement, if you are calling a routine which is defined after the calling statement. A routine returns the value of the last expression back to its caller, or returns with an explicit RETURN statement. 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;

A variable defined in a routine is only visible inside the routine scope.

Variadic

We can't tell the exact arity that a routine receives while defining it sometimes; MY-BASIC uses variadic for this case. Use the variadic symbol, with triple dots, in the parameter list of a routine to represent "any numbers of arguments"; or pass it to a routine to tell it to take as many as it goes; the symbol ... pops arguments literally when using it in a routine body. For example:

def foo(a, b, ...)
	return a + " " + b + " " + ... + ...
enddef

def bar(...)
	return foo(...)
enddef

print bar("Variable", "argument", "list", "...");

Use the LEN statement to tell how many arguments are remaining in a variadic list as LEN(...). Enumerate all arguments as follow:

l = len(...)
for i = 1 to l
	s = s + ...
next

Or:

while len(...)
	s = s + ...
wend

Or:

t = 0
do
	s = s + t
	t = ...
until type(t) = type("unknown")
Clone this wiki locally