lua-users home
lua-l archive

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



On 28-Oct-04, at 11:40 AM, George Warner wrote:

Is this true?

Probably not.

 Do "local" variables have a life beyond their scope?

No.

Do they waste memory?

Possibly. Consider the following:

local a = {}
for i = 1, 1000000 do a[i] = "X" .. i end
local b = somefunction(a, x)
-- no more references to a

In that case, a will live until the end of the scope, which
might be some time distant.

It is better to create such locals within their own scope,
although that is a bit awkward in the above case; it looks
like this:

local b -- create b in surrounding scope
do
  local a = {}
  for i = 1, 1000000 do a[i] = "X" .. i end
  -- use b from surrounding scope:
  b = somefunction(a, x)
end

Of course, that's a dumb example.

For what it's worth, the following code is probably better:

-- useful helper function, makes maintenance easier
local function Set(s)
  local t = {}
  for w in string.gfind(s, "([%S]+)") do t[w] = true end
end

-- Who are the stooges?
local Stooges = Set[[ Larry Curly Moe ]]

-- ....
   if Stooges[GetUserName()] then
     print "Dude, you're a Stooge!"
   end