Blog Archives

applescript: get item number of list item

Screen Shot 2016-07-31 at 21.45.31

One of the annoying ‘missing features’ in AppleScript is the lack of any way to get the item number of an item in a list.

Fortunately, since Cocoa does of course include an ‘indexOfObject’ function, we can leverage Cocoa in our AppleScript to write a nice little handler (you could add this to my list and string handlers library I posted here or just add it directly in your own scripts).

First, make sure your script or library already has two lines like these to import the Foundation framework and declare an NSArray:

use framework "Foundation"

property NSArray : a reference to current application's NSArray

Then after that add the handler:

on getIndexOfItem:anItem inList:aList
set anArray to NSArray's arrayWithArray:aList
set ind to ((anArray's indexOfObject:anItem) as number) + 1 # see note below
if ind is greater than (count of aList) then
display dialog "Item '" & anItem & "' not found in list." buttons "OK" default button "OK" with icon 2 with title "Error"
return 0
else
return ind
end if
end getIndexOfItem:inList:

You can now call the code like this:

# example
set thisList to {"I", "see", "a", "red", "door", "and", "I", "want", "to", "paint", "it", "black"}
set aNum to its getIndexOfItem:"paint" inList:thisList
(* Result --> 10 *)
if aNum is not 0 then
-- do something
end if

# Note: Remember AppleScript lists are indexed from 1, unlike Cocoa arrays which start at index 0.

Enjoy! 🙂

will Mountain Lion work on my old mac?



If you’re wondering whether your machine can be upgraded to run OS X 10.8 Mountain Lion, you can check the full list of supported models below.

To find out which model of mac you’ve got, hold down the option key on your keyboard and select

 > About This Mac

Check the ‘Model Identifier’ against this list:

MacBookPro4,1
Macmini5,3
Macmini5,2
Macmini5,1
MacBookPro5,1
MacPro4,1
MacBookPro5,2
iMac8,1
MacBookPro5,4
MacBookAir4,2
iMac11,1
iMac11,2
iMac11,3
MacBookPro8,2
MacBookPro3,1
MacPro5,1
iMac9,1
Macmini3,1
MacBookPro6,1
iMac12,2
iMac12,1
MacBook5,1
MacBook5,2
iMac10,1
MacBookPro7,1
MacBookAir4,1
MacBookPro5,3
MacBookPro6,2
MacBookPro5,5
MacBookAir3,1
MacBookAir3,2
Macmini4,1
Xserve3,1
MacBookAir2,1
MacBookPro8,1
MacBook7,1
MacBookPro8,3
iMac7,1
MacBook6,1
MacPro3,1

Of course, just because your machine’s listed, it doesn’t mean it will necessary meet all the specifications, so be sure to check the tech specs too.

🙂

%d bloggers like this: