defining and using globals in an application

Richard Gaskin ambassador at fourthworld.com
Thu Jul 7 09:38:58 EDT 2011


Mark Stuart wrote:
> You HAVE to declare the global again, and again where needed.
>
> I'd rather it once declared and a value put into it, the value be available
> elsewhere WITHOUT having to declare it again.

As Jacque pointed out, LC and related dialects are very forgiving with 
the scope of variable names, so it's possible to have one token used as 
a global, a local, and an argument.  To avoid confusing the compiler, we 
need to declare globals in any script that uses them.

If that one line of code at the top of a script is cumbersome (and in 
some complex code bases it may well be), try accessors instead:

-- In a mainstack, library, backscript, or other globally-available
-- script:
global gDefaultWidgetHeight

command SetDefaultWidgetHeight pVal
   put pVal into gDefaultWidgetHeight
end SetDefaultWidgetHeight

function GetDefaultWidgetHeight
    return gDefaultWidgetHeight
end GetDefaultWidgetHeight
---

With those in place you can get and set the value stored in the global 
from any other script without a declaration, e.g.:

   set the height of grp 1 to GetDefaultWidgetHeight()
   SetDefaultWidgetHeight 200

Another benefit to using accessors is that they help factor code; that 
is, you can change how you store that value at any time without having 
to modify any code that relies on it.  Today it might be a global, but 
two versions from now it might be a database record; with accessors, you 
only change two handlers and everything else comes along for the ride.

True, using accessors will impair performance relative to calling the 
global directly.  But in practical terms you're only looking at a 
fraction of a *micro*second, so if you need to liberate your code base 
from direct storage references chances are no one will ever notice the 
performance difference.

--
  Richard Gaskin
  Fourth World
  LiveCode training and consulting: http://www.fourthworld.com
  Webzine for LiveCode developers: http://www.LiveCodeJournal.com
  LiveCode Journal blog: http://LiveCodejournal.com/blog.irv




More information about the use-livecode mailing list