[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Globals (more ruminations)
- From: Patrick Donnelly <batrick@...>
- Date: Thu, 8 Jul 2010 13:16:46 -0400
Hi Mark,
On Thu, Jul 8, 2010 at 12:45 PM, Mark Hamburg <mark@grubmah.com> wrote:
> Why are globals "bad"?
>
> The primary reason is the same reason they are "bad" in other languages: They create opportunities for unexpected coupling. Code in one script can unexpectedly interact with code in another script through shared global names. This problem can be mitigated by assigning each script its own environment table when it is loaded. These tables can use a metatable with an __index entry to access an intentionally shared namespace of values. It is also worth noting that this sort of coupling is exactly why globals are useful in interactive mode where we need to tie together a series of separately compiled chunks.
>
> (Side note: Unexpected coupling is also why having the module function add the module to the global namespace is "bad".)
Coupling is certainly one issue. A major problem Nmap's NSE (Nmap
Scripting Engine) has had is libraries used by multiple scripts
accidentally using a global instead of a local. Note that these
libraries use module so each one has its own environment. Still, all
our scripts are coroutines so they step on each others' toes when
setting/getting globals within the library! (For example, an http.get
function would have a global (when it should be local) socket variable
it would set and use. Other scripts would overwrite this variable when
also using http.get!) This has been an insidious problem for us and
I've had to write custom scripts to look for these accidental global
accesses. It would be *superb* if there were some sort of compile time
solution to this.
--
- Patrick Donnelly