[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Question about Lua performance (locals vs globals)
- From: David Manura <dm.lua@...>
- Date: Fri, 8 Aug 2008 00:41:51 +0000 (UTC)
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
> > > internally. When you access a local, it's referred to directly
> > > 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.
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 .
> 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". For example, they are more amenable to
 "15. Use const proactively" in "C++ Coding Standards: 101 Rules, Guidelines,
and Best Practices". http://acmsel.safaribooksonline.com/0321113586/ch15