What is a repeat loop and what is the "i" in "repeat with i in x"?

A repeat loop is a control structure which allows you to automate repetitive and iterative tasks. For example:

repeat
	set currentYear to year of (current date)
	if currentYear is 2005 then exit repeat
end repeat

If you run this script during the year 2004, it should keep running till year 2005, checking periodically (very short intervals) if the current year is 2005, when it will exit of the repeat loop.

You can repeat a specified number of times. For example, this would beep 5 times if it was 5 AM in the clock:

set H to word 1 of time string of (current date) as number
repeat H times
	delay 1
	beep 1
end repeat

Also, you can iterate through items in a list. That is most probably because you find lots of times the character “i” in such repeat loops (though you can find “x” or “myMother” or whatever other variable name…):

repeat with i in characters of "Joe"
	display dialog i
end repeat

As you see, the variable “i” acquires the value of the subsequent item in the list, one each iteration: J, o, e.

You can also use iterating variables with numbers:

repeat with i from 1 to 4
	display dialog i
end repeat

If you run the example, you will se that it is easy… And here is a backwards variation:

repeat with i from 5 to 1 by -1
	display dialog i
end repeat

You can also “repeat”, iterating if a certain condition is true:

set x to 0
repeat while x is not 5
	set x to x + 1
end repeat

And a variation using a “until” clause:

set x to 0
repeat until x is 5
	set x to x + 1
end repeat