Tuesday, March 29, 2011

AutoIT Variable Types

Dim, Global, and Local
There are three types of variables in AutoItT:

Dim
  Declaring a variable using Dim gives it the scope of its current location within   the script. If the variable is declared outside any functions, its scope is global.

  The following is an example of declaring a Dim variable in the global scope. It
runs setup.exe in the directory where the script is located:

Code:
Dim $variable = @ScriptDir & "\setup.exe"
  Run($variable)

  The next example shows how declaring a Dim variable inside a function allows it only Local scope and how the variable is destroyed once the function is complete.
 The result is a script that errors out when run because $variable is not declared globally:

Code:
function()
  Func function()
    Dim $variable = @ScriptDir & "\setup.exe"
  EndFunc

  Run($variable)

 You should explicitly declare variables as Global or Local to avoid problems. If a Dim variable is declared inside a function but a Global variable already exists, the Global variable is overwritten. The following example shows what happens if a Global variable exists when the same variable is declared as Dim within a
function. The result is that setupbad.exe runs instead of setup.exe; the Global $variable is modified to setupbad.exe because Dim was used to declare the variable locally within the function:

Code:
Global $variable = @ScriptDir & "\setup.exe"
  function()

  Func function()
    Dim $variable = @ScriptDir & "\setupbad.exe"
  EndFunc

  Run($variable)

Global
  This type of variable can be read from or written to from anywhere in the script.
Global variables can be used in functions without being destroyed when the
functions complete. The following is an example of declaring a Global variable:

Code:
  Global $variable = 2

Local
 A Local variable is used in the scope of a function. Once the function is complete,the variable is destroyed. If a Global variable of the same name already exists, the function modifies the Global variable and it is not destroyed when
the function completes. Variables are always checked in the local scope first,
then in the global scope. The following example shows the use of a Local variable
within a function:

Code:
function()
  Func function()
    Local $variable = @ScriptDir & "\setup.exe"
    Run($variable)
  EndFunc

No comments:

Post a Comment