I am having trouble setting these variable. There are 4 differrent names that target_camera could be (living room, kitchen, frontyard, or XXX). I want to set the variable itemNumber to 1,2,3,4 according to what target_camera is. If it is not one of the four options, I want itemNumber to be 0. Any ideas? I am not having good luck.
if target_camera is "living room" then
set itemNumber to 1
if target_camera is "kitchen" then
set itemNumber to 2
if target_camera is "front yard" then
set itemNumber to 3
if target_camera is "xxx" then
set itemNumber to 4
else
set itemNumber to 0
end if
if target_camera is "living room" then
set itemNumber to 1
else
if target_camera is "kitchen" then
set itemNumber to 2
else
if target_camera is "front yard" then
set itemNumber to 3
else
if target_camera is "xxx" then
set itemNumber to 4
else
set itemNumber to 0
end if
end if
end if
end if
Or using the compressed “if” format, this translation of Scott’s script:
set reports to {}
repeat with k from 1 to 5
set target_camera to item k of {"living room", "kitchen", "front yard", "xxx", "foo"}
if target_camera is "living room" then
set itemNumber to 1
else if target_camera is "kitchen" then
set itemNumber to 2
else if target_camera is "front yard" then
set itemNumber to 3
else if target_camera is "xxx" then
set itemNumber to 4
else
set itemNumber to 0
end if
set end of reports to itemNumber
end repeat
reports
--> {1, 2, 3, 4, 0}
if target_camera is "living room" then
set itemNumber to 1
else if target_camera is "kitchen" then
set itemNumber to 2
else if target_camera is "front yard" then
set itemNumber to 3
else if target_camera is "xxx" then
set itemNumber to 4
else
set itemNumber to 0
end if
Well, that’s certainly alot cleaner… but what’s the point of the repeat, Adam?
Also, if the list gets very long, rather than write a huge list of “else if” statements, use this approach:
property Camera : {"living room", "kitchen", "front yard", "xxx"}
set target to "kitchen"
getCameraNum(target)
to getCameraNum(TC)
set CN to 0
repeat with k from 1 to 4
if TC is item k of Camera then set CN to k
end repeat
return CN
end getCameraNum
… and an ‘exit repeat’ would save having to iterate right through to the end of the list after the target was found:
to getCameraNum(TC)
set CN to 0
repeat with k from 1 to (count Camera)
if TC is item k of Camera then
set CN to k
exit repeat
end if
end repeat
return CN
end getCameraNum
I stuck the repeat in just to illustrate that it worked - it just runs through all the options and collects all the results, including the null result. The piece you’ve quoted is the “guts of it” as you realized yourself.
I force myself to use this construction where it makes sense because when you come back to it later it’s waaaay easier to figure out what it’s doing.