Try example 1, then try example 2.
Why does example 1 not work?
set example to 0 --enter example number here
global a
on a()
return 1
end a
global b
on b()
return 2
end b
-- Example 1: This doesn't work, ...
on c()
set r to some item of [my a, my b] --line 1
return r() -- line 2; AppleScript Error: «script» doesn't understand the r message.
end c
if example = 1 then
c()
end if
--Example 2: ... but this works
if example = 2 then
set r to some item of [my a, my b] -- the same line 1
return r() -- the same line 2; returns 1 or 2
end if
weird syntax.
First of all, lists are wrapped in braces, not brackets.
Second, I donât know, why the second example works,
but the first example doesnât work, because youâre messing up variables and handlers
set example to 1 --enter example number here
on a()
return 1
end a
on b()
return 2
end b
-- Example 1: This doesn't work, ...
on c()
set r to some item of {a(), b()} --line 1
return r
end c
if example = 1 then
c()
end if
--Example 2: ... but this works
if example = 2 then
set r to some item of {a(), b()} -- the same line 1
return r -- the same line 2; returns 1 or 2
end if
Note: the global statements are useless, handlers on the top level are global anyway
Handler labels, as Stefan says, are globals â and in fact have to be. In your Example 1, the variable r is, by default, local to the handler c(). If you want to use it to call a handler, it has to be declared as a global:
set example to 1 --enter example number here
on a()
return 1
end a
on b()
return 2
end b
on c()
global r
set r to some item of {a, b}
return r()
end c
if example = 1 then
c()
end if
A handler can be assigned to a local variable, but it can only be called with a global one.
In your Example 2, r isnât in a handler, but is what we call a âtop levelâ or ârun handlerâ variable. These are like globals and properties in that theyâre permanent properties of the script (as opposed to being temporary variables in handlers), but are local (except where declared otherwise) in that they canât be seen from within handlers. In this case, râs global/property-like nature allows it to be used as a handler label.
There are other ways of choosing between handlers, but this should answer your immediate query.