Sub

Sub
Run BASIC supports subroutines. They are defined with **Sub** and they must end with an **End Sub** statement. Subs are invoked with the **Call** statement. Variables inside subs are local to the sub. Variables in the main program are not visible inside the sub unless they have been declared Global.

The syntax for these statements is as follows:

SUB subName[, param1[, param2...]] //- Define a subroutine subName with optional parameters// END IF/SUB/FUNCTION/SELECT/DIV //- Specify the end of an IF/SUB/FUNCTION/SELECT/DIV block// CALL subname[, param1[, param2...]] //- Invoke subname with one or more parameters//

The parameter list is separated by commas. The parameters are not surrounded by parentheses. Paramenters can be both string and numeric types. A sub needn't have any parameters at all.

The code listing should not fall into a sub. A Wait statement in the line before the **Sub** definition guarantees that the program will not procede into the **Sub**.

Here is a typical sub with no parameters:

code Sub Hello print "Hello, World!" end sub code

Here is a program that invokes this sub. Notice that the program halts at a Wait statement before it reaches the **Sub** definition.

code format="vbnet" call Hello wait

sub Hello print "Hello, World!" end sub code

Here is a program that invokes a sub to add two numbers and print the result.

code format="vbnet" call AddMe 32, 1.5 wait

sub AddMe num1, num2 print num1 + num2 end sub code

The following program invokes a sub to print the name (as string) and ID number (as number.)

code format="vbnet" call DoGuy "Joe",59 wait

sub DoGuy person$, idNum html "";person$;"'s ID Number is ";idNum end sub code

Here are all three subs in a single program:

code format="vbnet" call Hello call AddMe 32, 1.5 call DoGuy "Joe",59 wait

sub Hello print "Hello, World!" end sub

sub AddMe num1, num2 print num1 + num2 end sub

sub DoGuy person$, idNum html "";person$;"'s ID Number is ";idNum end sub code

The output:

code Hello, World! 33.5 Joe's ID Number is 59 code

The following program assigns values to two variables in the main program. One of the variables is declared Global. Notice that the value of the global variable is visible inside the sub. The value of the other variable is not visible in the sub. The variable "Num" is local to the sub and has no value.

code format="vbnet" global Total Total = 256 Num = 1024

call PrintVars wait

sub PrintVars print "Total is ";Total print "Num is ";Num end sub code

Output:

code Total is 256 Num is 0 code