Home > Language Reference > Introduction to the Language > Visibility of Variables

Visibility of Variables

The following examples show how to use LOCAL keyword and how it affects variable contents.

Example 1
Sub addition()
    Res=number1 + number2
    msgbox(res)
    EndSub
    'main program
    number1=5
    number2=6
    addition()
The displayed result is 11. Number1 and number2 are seen as integer global variables and so are known within the subroutine.

Example 2
Sub addition()
    Local number2
    Res=number1 + number2
    msgbox(res)
    EndSub
    'main program
    number1=5
    number2=6
    addition()
The displayed result is 5. Number1 and number2 are seen as integer global variables, but as within the subroutine number2 is declared as LOCAL, during procedure execution, global variable number2 is masked. And local number2 variable is automatically initialized at 0.
When the procedure is executed, each time it refers to variable number2, it uses local number2 and not global number2.
Integer global number1 variable is known within the procedure, and so this procedure adds 0 (local variable number2) and 5 (global variable number1).

Example 3
Sub addition()
    Local number3
    number3=number1 + number2
    msgbox(number3)
    EndSub
    'Main program
    number1=5
    number2=6
    addition()
    msgbox(number3)
The first message box displays 11. The second displays 0. Number1 and number2 are seen as integer global variables and so are known within the procedure. But number3 is local to the procedure ; it exists only at procedure execution and so its value in main program is 0, default value for an integer variable not yet initialized.

Example 4
Sub addition()
    Local number3
    number3=number1 + number2
    msgbox(number3)
    EndSub
    'Main program
    number1=5
    number2=6
    number3=4
    addition()
    msgbox(number3)
The first message box displays 11. The second displays 4. Number1 and number2 are seen as integer global variables and so are known within the procedure. But number3 is local to the procedure : during procedure execution, each time it refers to number3 variable, it refers to local number3 and not global number3. First message box refers to local number3 during procedure execution, second message box refers to global number3, which has not been modified.

See also

Using Functions
Constants and Variables
Using Arrays
Expressions and Operators
Global and Local Variables
Script Structure