AppleScript - can't get "If" statement to work

I have this simple Applescript:


set theListOfValues to "apples oranges pears"
set AppleScript's text item delimiters to " "
repeat with theCurrentValue in text items of theListOfValues
  if theCurrentValue is "oranges" then
       log "Found it"
  end if
end repeat
log "End"
set AppleScript's text item delimiters to ""

I can't get the "if" test to find "oranges". It always resolves to false and so "Found it" is never logged.


What basic log am I missing here ? Why is the theCurrentValue "oranges" never equal to "oranges" ?


This is driving me barmy at present. I've scoured the Applescript language guide and Googled for hours but still can't figure out what I'm doing wrong.


Thanks.

Accepted Reply

When using the repeat with X in Y form, your comparison is to a reference, e.g. item 2 of someList. AppleScript doesn't automatically dereference the loop item, so unless a dereference needs to be done for some other part of the script or statement, you need to do it, for example:


    if theCurrentValue as text is "oranges" then ...
        -- or --
    if contents of theCurrentValue is "oranges" then ...

Replies

When using the repeat with X in Y form, your comparison is to a reference, e.g. item 2 of someList. AppleScript doesn't automatically dereference the loop item, so unless a dereference needs to be done for some other part of the script or statement, you need to do it, for example:


    if theCurrentValue as text is "oranges" then ...
        -- or --
    if contents of theCurrentValue is "oranges" then ...

Many thanks. This is starting to make sense. But, I've not found documentation which makes this clear. I've Googled quite a lot and read relevant parts of the langauge guide (2013). Page 258 of the language guide does state that the X variable is a "reference to an item in a list" which doesn't sit precisely with the contents of the X variable being the same as the relevant item in the Y list variable. I've thought that a variable has metadata (eg. name, type) and contents. The contents can be an array or matrix and so perhaps the content of the X variable is the content of the list item in one element and the index for that list item in a second element. Still, I'm only guessing – don't understand what a "reference" is.


Can you recommend a better source ?

You can use the contents property to get the value of an object that is being referenced (in this case, a relative object specifier for an item in the list, which can be anything). AppleScript will resolve a reference if it needs to for a particular command or operation (coercing to text, for example), but it doesn't do this automatically.


Additional documentation (such as it is) is buried in the section about Object Specifiers, which takes a while to wrap your brain around - References and Object Specifiers are a couple of those "features" that make AppleScript so frustrating.

Many thanks.