Repeating things

a simple loop

Sometimes you want to do something “forever” or as long as the script runs. Or you want to do it several times, but you don’t know exactly how long. For those cases, enclose it in a Loop-block:

1 ; any AutoHotkey version
2 Loop
3 {
4 	MsgBox Loop iteration %A_Index%
5 }

As you see above, the built-in variable A_Index contains the current iteration count. If you just want to repeat one line, you can leave out the braces.

As the above may consume a lot of memory, you may want it to wait some time before the next iteration:

1 ; any AutoHotkey version
2 Loop
3 {
4 	MsgBox Loop iteration %A_Index%
5 	sleep 1000 ; waits 1000 ms = 1 s before going on
6 }

SetTimer

For less memory consumption and to be able to do other things during the “wait-period”, you can also use SetTimer instead of a loop.

repeating x times

Sometimes you also want to repeat something but only a certain number of iterations. That’s very easy:

1 ; any AutoHotkey version
2 Loop 10 ; does 10 iterations
3 {
4 	MsgBox Loop iteration %A_Index%
5 }

You can also use a variable here. There’s only a slight difference in AutoHotkey v2 and AutoHotkey_H v2: In all other versions, you must enclose the variable in percent signs. In AutoHotkey v2 and AutoHotkey_H v2, leave the percent signs out (Loop accepts an expression parameter).

break and continue

During loop execution, you may sometimes discover something which should stop the loop or the current iteration. In all kinds of loops presented here (except for SetTimer, which isn’t a real loop), you can use break to stop the loop, and continue to skip the rest of the current iteration:

1 ; any AutoHotkey version
2 Loop
3 {
4 	if (breakNow)
5 		break
6 	if (skipIteration)
7 		continue
8 	; do something here that may change "breakNow" or "skipIteration"
9 }

while & until

If there’s only one condition that may cause a break, you way also use a while-loop or a loop-until.

1 ; any AutoHotkey version
2 While (!breakNow)
3 {
4 	; do something that may change "breakNow"
5 }
1 ; AutoHotkey_L, AutoHotkey_H, AutoHotkey v2 and AutoHotkey_H v2
2 Loop
3 {
4 	; do something that may change "breakNow"
5 } until breakNow

The difference is that while checks the condition before the iteration, whereas until checks it after the iteration (so there’s always at least one iteration).

for (each)

AutoHotkey has also a for loop (which corresponds to foreach in many other languages). We will cover this when dealing with objects later.

Loop parse, reg, file, …