Confused by Handlers...

Whenever I do anything in a handler, the variable always resets to the original value once the handler is finished. Am I doing something wrong, or is this normal behavior? Do handlers only allow variables in, but not out? See script below for an example:

-- Handler to add 2 variables
on addnumbers(number1, number2)
	set mySum to number1 + number2
	display dialog "Inside Handler:
	Sum is " & mySum default button 1 buttons {"OK"}
end addnumbers

set number1 to 25
set number2 to 75
set mySum to 0

-- sum should be 100
addnumbers(number1, number2)

-- but Handler ends, and sum is still 0
display dialog "Outside Handler:
	Sum is " & mySum default button 1 buttons {"OK"}

You need to remember that the default setting for any variable in AppleScript is local, meaning that if you use the same variable name within a handler, it will not replace the value of that variable outside the handler unless you declare the variable as global. Here is your script with that change:


global mySum
-- Handler to add 2 variables
on addnumbers(number1, number2)
	set mySum to number1 + number2
	display dialog "Inside Handler:
	Sum is " & mySum default button 1 buttons {"OK"}
end addnumbers

set number1 to 25
set number2 to 75
set mySum to 0

-- sum should be 100
addnumbers(number1, number2)

-- but Handler ends, and sum is still 0
display dialog "Outside Handler:
	Sum is " & mySum default button 1 buttons {"OK"}

It is usually considered good practice to use separate variable names within a handler, unless you specifically need the handler to work on something that has already been defined, like a list, or a record, or something like that.

Hope this helps.

-- Handler to add 2 variables
on addnumbers(number1, number2)
	set mySum to number1 + number2
	display dialog "Inside Handler:
	Sum is " & mySum default button 1 buttons {"OK"}
	return mySum -- return the answer
end addnumbers

set number1 to 25
set number2 to 75
set mySum to 0

-- sum should be 100
set mySum to addnumbers(number1, number2) -- set the value with the handler

-- but Handler ends, and sum is still 0
display dialog "Outside Handler:
	Sum is " & mySum default button 1 buttons {"OK"}

Oops - Craig was faster than a speeding bullet

-- if you want the handler to "know" and return the value then"

property mySum : missing value

to addNums(p, q)
	set mySum to p + q
end addNums

set x to 25
set y to 75
addNums(x, y)

mySum --> 100

Thanks guys… this makes handlers much more useful for my needs…

If you have some time, you might take a look at these articles in our unScripted archives about handlers:

Part One
Part Two

There may be others as well, but these are the freshest, and have some excellent tips.

Part III is running right now: Getting Started with Handlers (Part 3)