lua-users home
lua-l archive

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


On 12/30/06, Aladdin Lampé <genio570@hotmail.fr> wrote:
In Lua, I often do the same:
local a = ""
for ...
  a = ... -- use variable a, change its value, etc. (here variable 'a' is
'non-local' thus with no indexed search)
end

Variable 'a' _is_ still local, just the scope encloses the loop.  You
could do a 'local a' at the very beginning of the chunk and it would
still be local, just w/ its scope larger than you'd want, probably.

Would it be better Lua programming (in terms of *speed* optimization) to do
directly:
for
  local a = ... -- because here the variable 'a' is local and not
'non-local', thus very quickly resolved (indexed) even if recreated at each
loop
end

If you are 'just' doing assignment to the local 'a' and it's not some
object you are operating on, this makes more sense, unless you need
'a' outside the loop.

Note: in both cases you could just do 'local a' w/o any assignment.
It's just a shortcut w/ local a = ""

Here's an example case where keeping 'a' around makes sense.

local a = {}
for ...
 a[1] = someFunction()
end

Is cheaper than
for ...
 local a = {}
 a[1] = someFunction()
end

Tables and userdata are the kind of data you want to avoid unnecessary
re-allocations.
..  Jus' my first 2 cents in the new yr.
--
Thomas Harning Jr.