Skip to content

Sub routine

Wang Renxin edited this page Nov 4, 2017 · 20 revisions

This page describes how to define a sub routine and call it in script. For another topic about call from script to C and from C to script, see another Callback page.

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.

How to use

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 routine scope.

Tail recursion

MY-BASIC supports recursive sub routines and tail recursion optimization.

Variadic arguments

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

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

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

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

Use the LEN statement to tell how many arguments are still there in a variadic argument list as LEN(...). We may write something like below to enumerate all arguments:

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