Variable Scope Problem

What mistake have I made?

I believe that I have provided the OP a clear, accurate and easily understood answer to their question.

It is global but have to be declared global!? What does that even mean?

For my own edification, I tested various scenarios involving globals and have included them below FWIW. Everything seems to work as expected.

-- script 1
-- this script fails because theText is not seen in the showDialog handler

set theText to "hello"
showDialog()
on showDialog()
	display dialog theText
end showDialog

-- script 2
-- this script works because theText is set global in the top-level script object

-- global theText
-- set theText to "hello"
-- showDialog()
-- on showDialog()
-- 	display dialog theText
-- end showDialog

-- script 3
-- this script works because theText is set global in the top-level script object (note global location)

-- set theText to "hello"
-- global theText
-- showDialog()
-- on showDialog()
-- 	display dialog theText
-- end showDialog

-- script 4
-- this script works because theText is set global in the top-level script object

-- global theText
-- on run
-- 	set theText to "hello"
-- 	showDialog()
-- end run
-- on showDialog()
-- 	display dialog theText
-- end showDialog

-- script 5
-- this script fails because theText is set global in the run handler

-- on run
-- 	global theText
-- 	set theText to "hello"
-- 	showDialog()
-- end run
-- on showDialog()
-- 	display dialog theText
-- end showDialog

-- script 6
-- this script works because theText is set global in the showDialog handlers
-- this also works if the run handler is explicit

-- set theText to "hello"
-- showDialogA()
-- showDialogB()
-- on showDialogA()
-- 	global theText
-- 	display dialog theText
-- end showDialogA
-- on showDialogB()
-- 	global theText
-- 	display dialog theText
-- end showDialogB

BTW, if this thread proves anything, it’s the wisdom of the OP’s comment…

yeah yeah, you shouldn’t use global variables

1 Like

To declare a global in a handler you would use this form:

On HandlerName ()
global A
--do your stuff
end HandlerName

The line “global A” declares A as a global making it accessible inside the handler (Unless it was declared a gobal outside of any handler, in which case it’s available in all the script’s handlers.

FWIW, I use properties all the time. I rarely use globals.

2 Likes