Keyword Reference

Dim / Global / Local / Const

Declare a variable, a constant, or create an array.

Dim [Const] $variable
Dim $array[subscript 1]...[subscript n]

 

Parameters

const [optional] If present, the Const keyword creates a constant rather than a variable.
$variable The name of the variable to declare.
subscript The number of elements to create for the array dimension, indexed 0 to n-1.

 

Remarks

The Dim/Local/Global keywords perform a similar function.
1. Declare a variable before you use it (similar to VBScript)
2. Create an array

Note: In AutoIt you can create a variable simply by assigning a value ($myvar = 0) but many people like to explicitly declare them.

You can also declare multiple variables on a single line:

Dim $a, $b, $c


And pre-initialize, if variable is not an array:

Dim $a = 2, $b, $c = 20



Creating constants can be done in a similar way:

Dim Const $a, $b, $c
Const $a, $b, $c
Const $a = 2, $b, $c = 20
Local Const $a, $b, $c


Once created you cannot change the value of a constant. Also, you cannot change an existing variable into a constant.



The difference between Dim/Local/Global is the scope in which they are created:
Dim = Local scope if the variable name doesn't already exist globally (in which case it reuses the global variable!)
Global = Forces creation of the variable in the Global scope
Local = Forces creation of the variable in the Local/Function scope

When using variables the local scope is checked first and then the global scope second.

When creating arrays you are limited to up to 64 dimensions and/or a total of 16 million element.

A unique feature is the ability to copy arrays like this:
$mycopy = $myarray
In this case $mycopy will be an exact copy of $myarray and will have the same dimensions - no Dim statement is required first. If the variable $mycopy was already an array or value it will be erased before the copy takes place.

To erase an array (maybe because it is a large global array and you want to free the memory), simply assign a single value to it:
$array = 0
This will free the array and convert it back to the single value of 0.

Dim for the same variable name will erase and reset the dimensions to the new definition.

 

Related

UBound, ReDim

 

Example

; Example 1 - Declaring variables
Dim $x, $y = 23, $z
Global $PI = 3.14159, $RADIUS
Local $daysWorking = 5

; Example 2 - Declaring arrays
Dim $weeklyWorkSchedule[$daysWorking]
Global $chessBoard[8][8]
Local $mouseCoordinates[2], $windowStats[4]

; Example 3 - Declaring constant variables
Const $x, $y = 23, $z
Global Const $PI = 3.14159, $RADIUS
Local Const $daysWorking = 5