18.4. Local and global variables

[<<<] [>>>]

In the example the local variable x is assigned a value, but is never used. Local variables in ScriptBasic serve the same purpose as in other languages. They are to store values for the time of function or subroutine execution. They are automatically created when a function or subroutine starts and vanish as the subroutine or function finishes its task.

Local variables are the only variables that have to be defined in ScriptBasic. If a variable is not declared as local then ScriptBasic will think that the variable is global. Global variables keep their values while the program executes. See the following example:

call MySub()
call MySub()
sub MySub
local x

print x," ",y,"\n" x = 3 y = 4 end sub

The output of the program is:

undef undef
undef 4

The variable y is not defined when the subroutine is called the first time. The variable x is local and is also not defined. When the program calls the subroutine the second time the local variable x is freshly created and therefore has no defined value. On the other hand the global variable has the value assigned to it during the previous subroutine call.

Local variables not only exist to create new local space. They can also help the programmer to protect global variables. A function or subroutine may use a variable named ExampleVariable and may alter the value of it. Other parts of the program may use the same variable without knowing that the variable value changes in the function or subroutine call. For example the program:

ExampleVariable = 3
call MySub()
print ExampleVariable
sub MySub
ExampleVariable = 5
end sub

prints out the value 5. If we alter the program

ExampleVariable = 3
call MySub()

print ExampleVariable sub MySub local ExampleVariable ExampleVariable = 5

end sub

the output becomes 3. The variable ExampleVariable is local in this second case and it does not interfere with the global variable of the same name.


[<<<] [>>>]