[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Globals (more ruminations)
- From: HyperHacker <hyperhacker@...>
- Date: Thu, 8 Jul 2010 16:27:46 -0600
On Thu, Jul 8, 2010 at 15:39, Henk Boom <henk@henk.ca> wrote:
> On 8 July 2010 12:45, Mark Hamburg <mark@grubmah.com> wrote:
>> As someone I think pointed out, the reason the globals issue seems to keep coming up is that globals are viewed as "bad" and Lua makes them easy to create. In addition, that ease of creation can also hide errors caused by typos.
>>
>> Why are globals "bad"?
>
> Actually, the main reason I think globals are bad is that it's too
> easy to use them by accident. Two situations I've hit are
>
> 1) I make a typing mistake and end up using an unused global instead
> of the local I meant. The only symptom is that one use of the variable
> seems to return nil.
> 2) I forget to declare a variable local, so that it ends up being
> global instead. Everything works fine until the function ends up being
> called re-entrantly, resulting in a tricky to find bug.
>
> That being said, I love how useful they are for making closure-based
> objects. Using setfenv I set it up so that globals are public fields,
> and locals are private fields, but both using the same syntax for
> accessing/setting.
>
> henk
>
There's also the case where you declare a local variable, maybe for
debugging, then later remove the declaration but fail to remove all
assignments. If this is a fairly generically-named variable and you
happen to have another with that name higher up in scope, suddenly
your variables are "randomly" changing in value.
The same of course can happen with a module that uses globals. Your
"socket" changes because one of the module functions also refers to a
"socket" in the global namespace. Or the module function simply
doesn't work because the value isn't what it expects.
Some will always reply "don't use modules that cause problems", but
that's not the solution to everything. If we didn't use software that
has bugs, I guess we'd all be potato farmers... ;-)
--
Sent from my toaster.