Sunday, December 21, 2014
  • Index
  •  » Core Language
  •  » What is a repeat loop and what is the "i" in "repeat with i in x"?

#1 2005-10-13 03:16:59 pm

julifos
Administrator
From: MalasaƱa, Madrid
Registered: 2002-11-20
Posts: 2014

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:

Applescript:

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:

Applescript:

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...):

Applescript:

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:

Applescript:

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:

Applescript:

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:

Applescript:

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

And a variation using a "until" clause:

Applescript:

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

Offline

 
  • Index
  •  » Core Language
  •  » What is a repeat loop and what is the "i" in "repeat with i in x"?

Board footer

Powered by FluxBB

[ Generated in 0.023 seconds, 10 queries executed ]

RSS (new topics) RSS (active topics)