lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sat, 24 Mar 2012 18:55:44 -0700 (PDT)
codemonkey Monkey <thecodemonkey@rocketmail.com> wrote:

> > From my reading of what you wrote above, you basically want every
> variable in every function to be, for want of a better word, a "public
> variable."
> 
> Well, I have a lot of local vars.  The Lua fns have "local foo=..."
> all over the place, so in that sense it's just like the out of the
> box Lua behavior.  Local vars are local, and once you don't declare
> local to go _G, or in my case, the particular environment I'm trying
> to use at the time.  I'm not trying to change the basic way Lua works
> in that sense, just trying to steer things over to a different table,
> but being able to chose that table on a callstack basis.
> 
> 
> CM

Hey Codemonkey, I just had a thought...

First, a disclaimer. I don't know how global variables work in any
language because I never use them, so I'm just reading your words and
trying to understand everything.

It sounds to me, from your words above, that all globals go in _G. Now
watch this...

Give _G a metatable that, when you're in diagnostic mode, errors out on
every global not specifically declared in _G's metatable (I have no
idea how to do this, but...). Now, when users of your object.method()
or object.property framework accidentally use method() or property,
when it's in diagnostic mode it errors out on every unintended global,
which is a defense against your very valid worry that leaving out the
object in object.property will silently fail in a different part of the
program.

Actually, in my personal opinion, global variables are so dangerous
that it makes sense to ask the programmer to explicitly declare them as
a global. As a matter of fact, I feel much more comfortable with
languages where local is the default, and you have to explicitly
declare all globals. I sometimes forget to put the word "local" (or
"my" in Perl), setting myself up for a later subtle bug.

I think this metatable for _G might go a long way to giving your
framework the robustness you're looking for.

SteveT