lua-users home
lua-l archive

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


As a long-time user of Lua in an environment where multiple scripters share a common global table (Girder 4), there is just one thing in Lua I'd really like to see changed. This is the automatic creation of variables in the global environment table.

I know there has been discussion of adding an explicit "global" keyword and an option to switch off automatic variable creation ("option explicit"). I'd like to suggest something slightly different.

My suggestion is that automatic variables should be local rather than global. To create or reference a global variable you'd have to use the "_G." prefix which is already available.

Where you currently create a global variable by writing:

x = 1

under my proposal, you'd write:

_G.x = 1

and the first statement would now be equivalent to:

local x; x = 1

This change would be more consistent with the lexical scoping of Lua and in practical terms would make accidental pollution of the global table less likely and easier to find using a simple search. It would also eliminate subtle errors were you think you are accessing a local variable but in fact are accessing a global with the same name. This proposal actually simplifies Lua by avoiding the need either for "local" OR "global" as a keyword.

However, as a separate but related proposal, a "using" keyword might be desirable - this would specify that, within lexical scope, a string-keyed table element will be specified using its key alone.

So you could write:
using _G.x; x = 1

This would work with any table, including deeply nested ones, not just _G.

If the first part of this proposal was adopted, transition would obviously be a problem. I'd suggest overloading the "using" keyword with "using global" and "using local" to allow specification, within a chunk, of the automatic variable policy. Anyone embedding Lua would be able to choose whether to preserve compatibility by making "using global" the default or to make "using local" the default and force scripters to change their code.

I really think this would be a big improvement to Lua both theoretically and practically and worth the undoubted pain of transition. Any comments?

- John Hind