You will often want to change the flow of your script based on a condition or series of conditions. Is one number bigger than another? Or, does a string contain a certain value?
Conditions are evaluated as true (non-zero) or false (zero). Conditions generally use comparison operators like ==, <>, >=.
The following conditional statements are available in AutoIt:
All three statements are similar and decide which code to execute depending on the condition(s) given. Here is an example of an If statement that pops up a message box depending on the value of a variable.
$var = -20
If $var > 0 Then
MsgBox(0, "Example", "$var was positive!")
ElseIf $var < 0 Then
MsgBox(0, "Example", "$var was negative!")
Else
MsgBox(0, "Example", "$var was zero.")
EndIf
In the example above, the expression $var > 0 evaluated to false because the variable was less than zero. When the first condition failed, the second condition was tested. The expression $var < 0 evaluated to true. This caused the If statement to execute the second MsgBox line and display "$var was negative!".
A Select statement is very similar, but is generally used for situations where you want to test a large number of conditions as it is generally easier to read than a large If/ElseIf type block. e.g.
$var = 30
Select
Case $var > 1 AND $var <= 10
MsgBox(0, "Example",
"$var was greater than 1")
Case $var > 10 AND $var <= 20
MsgBox(0, "Example",
"$var was greater than 10")
Case $var > 20 AND $var <= 30
MsgBox(0, "Example",
"$var was greater than 20")
Case $var > 30 AND $var <= 40
MsgBox(0, "Example",
"$var was greater than 30")
Case $var > 40
MsgBox(0, "Example",
"$var was greater than 40")
EndSelect
A Switch statement is very similar to Select statement, but is generally used for situations where the same expression is tested against some different possible values.
$var = 30
Switch Int($var)
Case 1 To 10
MsgBox(0, "Example",
"$var was greater than 1")
Case 11 To 20
MsgBox(0, "Example",
"$var was greater than 10")
Case 21 To 30
MsgBox(0, "Example",
"$var was greater than 20")
Case 31 To 40
MsgBox(0, "Example",
"$var was greater than 30")
Case Else
MsgBox(0, "Example",
"$var was greater than 40 or less or equal to 0")
EndSwitch
With each of these structures, the first condition that is true controls which group of statements get executed. All subsequent conditions and their associated statements get ignored.