By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Comparing Variables and Strings with AutoIt

AutoIt tutorial showing how to compare variables and strings using conditional statements.

Edited: 2013-08-07 11:42

When you want to compare variables, you will be using an if statement, sometimes combined with other code to accomplish the comparison that you wish for.

In many cases, when someone wants to compare two variables, it will be a matter of performing a simple if check – but often you will also want to perform some simple math on the variables, before they are checked. This can all be done in the same conditional statement, or you can do it before – its entirely up to you.

Simple Comparison in AutoIt

In this script, we will be comparing two variables to see if they match. Its recommended that you test this for yourself to get a better understanding of how conditional statements work. Create a new AutoIt script, then copy and paste the following code into SciTE, or whatever editor you are using. I.e.

$variable1 = "whatever"
$variable2 = "whatever"
If $variable1 = $variable2 Then
    MsgBox(4096, "Message", "The variables matched..")
EndIf

The above script will create a MsgBox, with the message The variables matched. Currently it will not do anything if the variables didn't match – so to make it return a different message on failure, we will be adding an Else case to the if check. I.e.

$variable1 = "whatever"
$variable2 = "whatever"
If $variable1 = $variable2 Then
    MsgBox(4096, "Message", "The variables matched..")
Else
    MsgBox(4096, "Message", "No Match")
EndIf

The above will produce a MsgBox with a message saying: No Match if the variables we compare do not match.

Comparison Operators

When we compare things trough scripting, we will be using different operators depending on what we want to know. In addition to the equals sign, there are also signs which allows you to ask if a given value is less than, or greater than another value. The Comparison Operators in AutoIt are as follows:

= Check if two values match. Case insensitive when dealing with strings.
== Check if two values match. Case sensitive when dealing with strings.
<> Not Equal To. The comparison is case-insensitive when dealing with strings.
< Checks if the first value is less than the second.
> Checks if the first value is greater than the second.
<= Checks if the first value is less than, or equal to the second value.
>= Checks if the first value is greater than, or equal to the second value.