Failed to create an infinite loop with “repeat with i”

I’m a little bit confused by AppleScript right now.

repeat with i from 0 to 5
	set i to i - 1
end repeat
(* i is 4 *)

This code does not create an infinite loop.

But if I use the same logic on JavaScript, this code will create an infinite loop.

I’m very confused by this right now. Am I missing something here?

At the top of the javascript loop, the value of i is incremented (i++); in the AppleScript loop, the value of i is set to a new value regardless of its existing value.

As Shane has mentioned, AppleScript’s repeat with n from begin to end by steps loops are different than JavaScript loops. The equivalent of a for loop in AppleScript is to write the 3 for loop statements yourself and in-line (normally a compiler places them for you).


-- for (int i = 0;i<5;i++)
set i to 0 -- statement 1 of a for loop
repeat
	-- loop controlling code
	if i < 5 then -- statement 2 of a for loop
		set i to i + 1 -- statement 3 of a for loop
	else -- if statement 2 returns false, break
		exit repeat
	end if

	-- your code here
end repeat

Thank you both for answering! :stuck_out_tongue: So the key is to manually control the index value when using loops in AppleScript.

I did some changes on my code, in the end I used the “repeat while” loop.

set i to 0
repeat while i < 5
	(* do something, if something comes up, set i to i - 1 in the end *)
	set i to i + 1
end repeat

An alternate scheme would be :

set i to 0
repeat
   (* do something, if something comes up, set i to i - 1 in the end *)
   set i to i + 1
   if i = 5 then exit repeat
end repeat

Oops, it’s quite what DJ posted.

Yvan KOENIG running El Capitan 10.11.1 in French (VALLAURIS, France) lundi 7 décembre 2015 16:24:05