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

Learn more

Autoit Loops

This Tutorial walks you through how to work with loops in AutoIt.

Edited: 2013-08-08 13:44

AutoIt Logo

Loops are usually very alike, in that they will usually need a counter and a way to increment the counter on each successful loop execution. The thing that is different about the available loops in AutoIt is the syntax – in other words, the way you write the loops.

Do Until

To create a Do Until loop, we will first delacre the count variable, this will be incremented on each loop execution.

Local $i = 0

Next we'll create the actual Loop, the until statement says that the loop should continue until the $counter equals 10, which will never happen as it is currently. I.e.

Until $counter = 10

For the counter to actually count, we will need to increment it, which can be done with the following piece of code.

$counter = $counter + 1

Do Until Example

Local $counter = 0
  MsgBox(0, "Value of $i is:", $i)
  $counter = $counter + 1
Until $counter = 10


The while loop begins with the while keyword, followed by a statement – while the statement is false, the loop will continue running.

$counter = 0
While $counter <= 5
    MsgBox(0, "Value of $counter is:", $counter)
    $counter = $counter + 1

As you can see, the syntax reminds a lot of that in the Do Until example.


The For loop may feel a bit different, or harder to use for some – but as a rule of thumb, you should just remember that the statement is written immediately after the For keyword. Also, the counter is automatically incremented after each loop execution, which eliminates the line that would otherwise perform this task – somewhat simplifying the code.

For $counter = 1 to 10
    MsgBox(0, "Counter: ", $counter)

Iterating Over Arrays and Objects

You can also use the For to loop trough arrays and objects, this can be done with the In keyword.

Local $aArray[4]

$aArray[0] = "Hallo"
$aArray[1] = 0
$aArray[2] = 1.9233
$aArray[3] = "Another String"

Local $string = ""
For $element In $aArray
    $string = $string & $element & @CRLF
MsgBox(0, "For..IN Arraytest", "Result is: " & @CRLF & $string)

You Iterate an object almost the exact same way as you would be handling an array. The following example will output your currently open windows in a message box.

Local $oShell = ObjCreate("shell.application")
Local $oShellWindows = $

If IsObj($oShellWindows) Then
    $string = ""

    For $Window In $oShellWindows
        $string = $string & $Window.LocationName & @CRLF

    MsgBox(0, "", "Your Current Open Shell Windows:" & @CRLF & $string)

    MsgBox(0, "", "You have no open Shell Windows.")

See also

  1. Creating an Infinite Loop