script editor

the following piece of AppleScript gives a false result. nameList is a list containing names. I have a second list called indexList which contains a list of indices to the nameList set of particular names requiring further investigation.


set cntr to the count of nameList

repeat with index in indexList

repeat with ind from 1 to cntr

if index is equal to ind then

-- process the corresponding entry in nameList

end if

end repeat

end repeat


This piece of code does not work. So I added a line to give me the class of both "index" and "ind". Both were described as "integer". However, when I added a further libe of "set index to index as integer" between the two repeat lines, the code starts to work correctly. Each time I got a match between "index" and "ind", I was now able to process the entry.

Why does this work when both variables had previously shown as class integer?

It’s hard to say what’s going on here without a concrete example. Can you post a snippet that includes an example

nameList
and
indexList
that demonstrates the failure?

ps It helps if you use the

<>
button to format your code in a code block.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

This question has nothing to do with Script Editor and really belongs on a general AppleScript forum (macscripter.net or discussions.apple.com/community/mac_os/mac_os_x_technologies).


But anyway, the problem is you misunderstand how `repeat with VAR in LIST` loops work. Variable VAR does not contain a list item, it contains a *reference* to a list item, e.g. `item 1 of LIST`. Depending on how you use that reference, it may get deferenced automatically and you’re none the wiser. However, when using it in equality operations (=, ≠) which do take value type into account, you must explicitly derefence it using `contents of REFERENCE`:


if contents of index is equal to ind then

end if


developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_control_statements.html

When using the repeat with X in Y form of the repeat statement, the loop variable X is actually a reference to an item in the list Y. Depending on what you are doing with the variable X, the value may not be dereferenced (yet), so comparisons can fail. To be sure you are using the value of X instead of its reference, you can coerce it to the desired class or get its contents, for example:


if contents of X = "whatever" then something


Also note that index is reserved word (note the different font in the Script Editor), and may result in unexpected behavior if used as a variable name.


(Edit: ninja'd by hhas01)

script editor
 
 
Q