lua-users home
lua-l archive

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

Thomas Lauer writes:
> Bryan White wrote:
> > David Given wrote:
> > > They actually work by totally different mechanisms. Lua locals are
> > > lexically scoped true variables, and exist on the Lua stack[1]
> > > internally. When you access a local, it's referred to directly[2]
> > > without any table lookup happening at all. Lua globals aren't really
> > > variables at all; they're simply syntactic sugar for doing table
> > > accesses on _G.

Or, more precisely, getfenv().

> As [David Given] pointed out, "global" is a clear misnomer here. The Lua
> documentation could usefully give better explanations as well as some
> guidance as to what "local" and "global" really means in a Lua context
> (and how both concepts could/should be used -- or not used). Someone
> coming from other languages (or even someone with no preconceptions)
> won't necessarily spot the interesting pitfalls hidden in these
> innocent-sounding words.

I actually said the same thing in an early encounter with Lua[1].

The refman does say, however, that "Local variables are lexically scoped...All
global variables live as fields in ordinary Lua tables...."  What this means in
practice is maybe less obvious.  If expanding upon this on the wiki, the proper
place would be [3].

> Many, if not most, of my scripts these days don't use globals at all.
> Not mainly because they're slightly faster that way, but because they're
> easier to understand and less error-prone.

Same here.  Locals (lexicals) restrict the semantics of the code.  Their use is
in some ways comparable to the use of const in C--they are "easier to
understand, track, and reason about"[4].  For example, they are more amenable to

[4] "15. Use const proactively" in "C++ Coding Standards: 101 Rules, Guidelines,
and Best Practices".