Global

=Global= toc

Variable Scope
Variables in Run BASIC are local in scope. This means that variables used inside subs and functions are visible only in those subs and functions. Variables inside subs and functions are not visible in other subs or functions, nor are they visible in the main program. Variables used in the main program are not visible inside subs or functions.

Exceptions
Special Runtime Variables used by Run BASIC are visible in all parts of the program. Their scope is global, not local.

You can create variables with a global scope that are visible in all parts of the program by using the **Global** statement. The syntax:

GLOBAL var1[,var2...] //- Define one or more variables to be globally visible.//

Both numeric and string variables can be declared as global. In addition handles (#handle) can be declared global too. Any number of variables can be declared as global in a single statement if separated by commas. Multiple global statements are also fine. Some sample global statements:

code global total, animal$, maxNum global fruit$ global lives, bullets, #handle code

Example Code
The following small program declares one variable, called "total" to be global in scope. The other variable, "total2" is local to the main program. When the **Sub** is called, it knows the value of "total", but not the value of "total2".

code format="vbnet" global total

total = 27 total2 = 468

call DisplayTotals wait

sub DisplayTotals print total print total2 end sub code

The output is: code 27 0 code

Because "total2" is local to the main program, it is not visible in the sub. It therefore becomes a **different** variable that is local to the sub. Even though it has the same name as "total2" in the main program, it is a different variable.

Here is a more complicated program. It creates two global variables in the main program. It also contains a variable local to the main program and another variable that is local to the sub. Notice how the global variables are visible in the sub, but the variables that are local to the sub are not visible to the main program.

code foramt="vbnet" global total, person$

total = 27 total2 = 468 person$ = "Carl"

call DisplayTotals print " " print "In main program:" print "PrettyColor$ is ";PrettyColor$ print "Done" wait

sub DisplayTotals print "In Sub:" print "Total is ";total print "Total2 is ";total2 print "person$ is ";person$ PrettyColor$ = "red" print "PrettyColor is ";PrettyColor$ end sub code

The output: code In Sub: Total is 27 Total2 is 0 person$ is Carl PrettyColor$ is red

In main program: PrettyColor$ is Done code