If I define global variables in a script, then call handlers from a script library, does the handler have access to the values of the global variables in the calling script?
Can called handlers from script library use globals from caller?
Short answer is: Yes!
My advice would be not to use it. Globals are bad and should be avoided in any situation. I know AppleScript is not an professional programming language but to avoid globals are for very good reason on any skill level.
I hear you, and generally agree.
I have one global variable, “gDebug”, that I use to toggle on/off debug code in handlers in my script library.
If I don’t use globals, what would you suggest to achieve this?
I should have been more clear about this. I meant global variables. The lack of global constants in AppleScript sometimes makes you use a global variable even if they are bad. Your global gDebug behaves more or less like a global constant and not a variable and it’s therefore “fine” to use it, or at least more acceptable.
But in an ideal solution every library should have it’s own debug flag so when debugging you can debug each library individually and aren’t bothered by any other libraries that are used by the script. The easiest way is writing an getter handler with no setter. gDebug isn’t variable but constant the entire time the program is alive which mimics more like a constant property.
For the record: We’re talking about libs which is something else than an instantiated script object that is under control of the root script object. For those sharing these global constants is normal, still I would prefer an get handler in the root script object that is accessible by parenting.
This would be my suggestion. Since AppleScript lacks the support of (global) constants it’s hard to tell which solution is best. My experience is based on applications on a much larger scale than an script. The chance of conflicts, pollution and unexpected results will grow with the size of the program.
Thanks. This sounds interesting, but I’m not sure I understand how to implement it.
- How would I toggle this debug flag?
- What is the handler getting? Why can I just use the debug flag directly in code, like:
if (gdebug) then -- do some stuff end if
If you have the time, providing a brief example would be great!
With constants you toggle at compile time.
It is much simpler. Instead of accessing a variable you use the outcome of an handler.
on gdebug() -- set to false to stop debug information set debugFlag to true return debugFlag end gdebug if gdebug() then -- do stuff end if run childScript script childScript if gdebug() then display dialog "debug information" end if end script
Keep in mind that there is a bug(?) in AppleScript. When using an local variable with the same name as the handler the parenting chain needs to be explicitly initiated with the continue statement.