A subroutine is like a sub-program which performs specific tasks independent of the main program body. A subroutine may be called several times from several places during execution of a program or from within other subroutines. When a subroutine is complete execution returns back to the next instruction following the subroutine call.

Subroutines are a powerful programming tool. Judicious use of subroutines (for example, through the structured programming approach) will often substantially simplify the development and maintenance of large programs, while increasing its quality and reliability. Subroutines can be collected into libraries that can be shared by several programs.

A subroutine may take a list of parameters (variables) which are pass to it from the calling program. All variables within a subroutine are local to that subroutine and are completely separate from variables in the calling program. A function is simply a subroutine that returns a value to the calling program.

All subroutines begin with a Sub command and end with an End Sub. For example:


Sub Test()
Print "Hello World"
End Sub

Any number of parameters may be passed to a subroutine. Parameters are separated by commas. For example:

w = 10
x$ = "World"
dim y(10)
y() = 5
dim z$(10)
z$() = "Hello"

Test(w, x$, y(), z$())

Sub Test(a, b$, c(), d$())
Print a, b$, c(0), d$(0)
End Sub

Normally parameters sent to a subroutine can not be modified by the subroutine. For example:

x$ = "I can't be changed."

Sub Test(a$)
a$ = "This won't change x$"
End Sub

If you want a subroutine to modify a calling parameter put a & before the variable parameter in the subroutine call. For example:

x = 1
print x

Sub Test(a)
a = a + 1
End Sub



Functions are simply subroutines that return values. For Example:

Notice the return statement at the end of the subroutine.

x = Test(5)
print x

Sub Test(a)
a = a * a
return a
End Sub


Functions which return string values must end the function name with a $.

print Test$()

Sub Test$()
return "Hello World"
End Sub

Hello World

Subroutines may call themselves recursively to any depth only limited by memory.

Subroutines that return values (functions) may not execute any commands that pause execution. These commands include Wait, Input, Edit, Progress, Touch. If a function attempts to execute a command that pauses execution, an error will be generated.

Functions have a heavy internal stack overhead and may be limited to 10-12 calls deep before you get a forced close. When writing recursive functions which go very deep use subroutines and pass values by reference. Subroutines which do not return a value do not suffer from stack limitations and may go thousands of calls deep.

Variables may be declared as global.


Subroutines may be grouped into reusable program files.


Become a Patron