Reverse repeat loop in list question.

Hi everyone,

I have a script (below) that searches in lists and leaves a result with all names (no duplicates) and their latest message. The problem is that the list starts searching in the beginning and not at the end. I know I have to use some “-” (negative) characters here and there but I can’t figure it out. Any help ? I want it to return {“Mark”, “My Last Message”, “Adam”, “My First Message”, “Jim”, “”}

set AllNames to {"Mark", "Jim", "Adam"}
set UsedNames to {"Mark", 2, 3, 4, "My First Message", "Adam", 2, 3, 4, "My First Message", "Mark", 2, 3, 4, "My Last Message"}
set LastMessages to {}

repeat with i from 1 to ((count UsedNames) / 5) -- I think this has to be repeat with i from -((count UsedNames) / 5) to -1 ?
	if AllNames contains (item (((i - 1) * 5) + 1) of UsedNames) and LastMessages does not contain (item (((i - 1) * 5) + 1) of UsedNames) then
		set end of LastMessages to (item (((i - 1) * 5) + 1) of UsedNames)
		set end of LastMessages to (item (i * 5) of UsedNames)
	end if
end repeat

(*This Part Works Fine*)
repeat with i in AllNames
	if LastMessages does not contain i then
		set end of LastMessages to i as text
		set end of LastMessages to ""
	end if
end repeat

LastMessages --> {"Mark", "My First Message", "Adam", "My First Message", "Jim", ""}

Thanks in advance

Retro, Im not 100% on this but think that when using the repeat with loop AppleScript will make a evaluation and assumption. If ‘from value’ is less than ‘to value’ and no ‘by’ is used then a value of ‘1’ is assumed. (could be wrong) If you try to do the reverse then the ‘by’ must be declaired. eg.

repeat with i from 2 to 8 by 2
	display dialog i
end repeat

results in 2, 4, 6, 8


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

results in 3, 2, 1

You can set which way a repeat runs:

repeat with J from bigCount to smallCount by -1

Oops – Mark67 was ahead of me. You can also simply reverse the original list: “set RList to reverse of OList”, and then use repeat with oneItem in RList…

Thanks both of you !
I didn’t know that those things were possible. I also didn’t know the reverse list command.

Thanks a lot ! :smiley:

To reverse a list use this simple command:


set AllNames to {"Mark", "Jim", "Adam"}
set ReverseAllNames to reverse of AllNames
-- the result: {"Adam", "Jim", "Mark"}

But still thanks SpiritBlade :slight_smile: