Re: Scope of globals, parents and children, "load script" an
Re: Scope of globals, parents and children, "load script" an
- Subject: Re: Scope of globals, parents and children, "load script" an
- From: email@hidden
- Date: Fri, 18 May 2001 02:52:28 -0400
On Thu, 17 May 2001 05:21:06 +0200, Sander Tekelenburg <email@hidden>
asked,
>
I'm trying to reorganize a rather large script (1000+ lines and growing) by
>
separating it into a main script (parent) and moving all handlers into a
>
separate script library (child) that is called by the main script with the
>
"load script" command.
For efficiency, you can load the libraries at compile time by making the "load
script" the value of a property:
property mathlib : load script alias "Disk:folder:Math Library"
>
However, I ran into something that tells me I seem to have problems
>
understanding the scope/meaning of globals. The original ('all-in-one')
>
script uses a lot of globals (17). To my surprise, I found that in order to
>
get everything to work, I needed to do 2 things in the script library :
>
>
1) declare those same globals again, at the top of the script
>
2) declare them yet again within each handler! (well, only those globals that
>
apply to that particular handler)
Any handler (which includes the implicit run handler of the main script) that
wants to use a global variable must declare it as such. The philosophy is that
an outsider can't steal a handler's variables. That is, an outside bunch of
code should not be able to change the meaning of code inside a handler by
declaring a variable global.
If I write,
on foo(x)
set i to 0
set x2 to x & x
set x3 to x2 & bar(x)
return x3 & (i as string)
end foo
Then it is a good thing that foo() doesn't unintentionally destroy the global
variables i, x2, and x3, just because some code outside foo() declared "global
x2". Its also good that bar() can't reach into foo() modify i when bar() is
called.
Taking a step back from the problem, it looks like you need to group your
handlers and the data they manipulate into script objects, rather than just
grouping the handlers into a library and ignoring the data. At very least, if
you set up the script object
script globe
property diameter : 40 as kilometers
property age : 4.3 * 10^9 * 365.25 * days
|rotation rate| : 1 / (24 * hours)
end script
you will get appropriate visibility, using the rules for inheritance of
properties that is documented in the AppleScript Language Guide, with examples
and all. In this case, when some code refers to "age of globe", the route taken
to resolve this is the route of the "tell globe to get age" message, through the
chain of inheritance to the main script.
--
Scott Norton Phone: +1-703-299-1656
DTI Associates, Inc. Fax: +1-703-706-0476
2920 South Glebe Road Internet: email@hidden
Arlington, VA 22206-2768 or email@hidden