defining and using globals in an application

Nonsanity form at nonsanity.com
Thu Jul 7 10:50:41 EDT 2011


On Thu, Jul 7, 2011 at 2:07 AM, Mark Wieder <mwieder at ahsoftware.net> wrote:

> Once again, no, it doesn't work that way. Global variables are *never*
> out of scope, so you can *not* have global and local variables with
> the same name. Even if the global variable is declared in a different
> script, it's still lurking in memory ready to bite you. You can not
> compile
>
> global xyzzy
>
> in one script and then try to compile
>
> local xyzzy
>
> in another script.
>

Actually you can, and I just tested it to be sure. I've got two buttons, one
with "global TestVar" and a mouseup handler that adds 1 to TextVar then
answers it, and a second button that has "local TestVar" and does the same
thing.

Clicking each in turn shows that the two values remain independent from each
other. This is because variables defined as global are only in scope if the
environment (usually a script) has defined the same global with the same
name.

A third button with just the mouseup script and no global or local always
displays "1" since the value of the handler-local TestVar is not preserved
from one execution to the next. It isn't automatically getting access to the
global declared in another script. It would have to be declared in each
script that wants to access it.

The message box is a special case where all globals are available to it
without having to explicitly declare them. (But not locals, of course, which
remain in-scope only within the script where they are defined.)

It doesn't bother the environment at all that a global and a local have the
same name, so long as they are defined in different scripts. (Actually, you
can define a local at the top of a script, then define the SAME name as a
global on the next line, and there won't be an error. Though the global line
WILL be ignored. Attempting the same thing in the opposite order results in
a compile error. Go figure...)

I always take a single page from the Hungarian Notation guidelines and put a
lowercase "g" before all global variable names. That way I always keep in
mind it's global nature, and I can never accidentally reuse the same name as
a local variable and get confused. (Note, only I would be confused by this,
not LiveCode.)

But I rarely use globals these days. I find using custom stack or card
properties work much better for most of the tasks I would have used a global
for. Plus they are preserved from session to session, unlike globals, and
can be made card-specific with the same name if needed.

It basically turns a single named storage location into a multi-named
storage location. Instead of just "TestVar" it would become "TestVar of card
1", etc. Custom properties are far superior to globals in functionality (in
my opinion) and more clear about scope.


Hope that helps,
 ~ Chris Innanen
 ~ Nonsanity



More information about the use-livecode mailing list