Scope and Life Span of Variables
A variable in Apache OpenOffice Basic has a limited life span and a limited scope from which it can be read and used in other program fragments. The amount of time that a variable is retained, as well as where it can be accessed from, depends on its specified location and type.
Variables that are declared in a function or a procedure are called local variables:
Sub Test Dim MyInteger As Integer ' ... End Sub
Local variables only remain valid as long as the function or the procedure is executing, and then are reset to zero. Each time the function is called, the values generated previously are not available.
To keep the previous values, you must define the variable as Static:
Sub Test Static MyInteger As Integer ' ... End Sub
Public Domain Variables
Public domain variables are defined in the header section of a module by the keyword Dim. These variables are available to all of the modules in their library:
Dim A As Integer Sub Test Flip Flop End Sub Sub Flip A = A + 1 End Sub
Sub Flop A = A - 1 End Sub
The value of variable A is not changed by the Test function, but is increased by one in the Flip function and decreased by one in the Flop function. Both of these changes to the variable are global.
You can also use the keyword Public instead of Dim to declare a public domain variable:
Public A As Integer
A public domain variable is only available so long as the associated macro is executing and then the variable is reset.
In terms of their function, global variables are similar to public domain variables, except that their values are retained even after the associated macro has executed. Global variables are declared in the header section of a module using the keyword Global:
Global A As Integer
Private variables are only available in the module in which they are defined. Use the keyword Private to define the variable:
Private MyInteger As Integer
If several modules contain a Private variable with the same name, Apache OpenOffice Basic creates a different variable for each occurrence of the name. In the following example, both module A and B have a Private variable called C. The Test function first sets the Private variable in module A and then the Private variable in module B.
Private C As Integer Sub Test SetModuleA ' Sets the variable C from module A SetModuleB ' Sets the variable C from module B ShowVarA ' Shows the variable C from module A (= 10) ShowVarB ' Shows the variable C from module B (= 20) End Sub Sub SetmoduleeA C = 10 End Sub Sub ShowVarA MsgBox C ' Shows the variable C from module A. End Sub
Private C As Integer Sub SetModuleB C = 20 End Sub Sub ShowVarB MsgBox C ' Shows the variable C from module B. End Sub
|Content on this page is licensed under the Public Documentation License (PDL).|