Handler, calling, and scope help needed

Try example 1, then try example 2.
Why does example 1 not work? :confused:

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

Hi,

weird syntax. :wink:
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.

I’m used to Python, where lists have to be in brackets and dictionaries (similar to records) are in braces.

No, I don’t want to call the handlers I’m not going to choose.

Thank you! That’s exactly what I’m looking for!:slight_smile: