lua-users home
lua-l archive

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



On 12-Dec-06, at 10:42 AM, Leo Razoumov wrote:

Hi Everyone,
I am puzzled by the behaviour of the following code:

function foo()
 local x= 1
 local x= 20
 local x= 300

<snip>

I am surprised to see that there are three different local 'x'
variables. All of them belong to the same "block" which is foo()
function body and, thus, should have the same scope. Why does not Lua
collapses them into just one local x variable??

Because they are three different variables which happen
to have the same name. (Some might consider that bad style.)

You don't need the debug library to see this:

function foo()
  local x = 1
  local function f1(inc)
    local old = x
    if inc then x = x + inc end
    return old
  end
  local x = 20
  local function f2(inc)
    local old = x
    if inc then x = x + inc end
    return old
  end
  local x = 300
  local function f3(inc)
    local old = x
    if inc then x = x + inc end
    return old
  end
  return f1, f2, f3
end

> x1, x2, x3 = foo()
> =x1(1), x2(1), x3(1)
1       20      300
> =x1(-2), x2(-2), x3(-2)
2       21      301
> =x1(), x2(), x3()
0       19      299


A slightly more interesting example:

function counters(...)
  local funcs = {}
  for i, init in ipairs{...} do
    funcs[i] = function(inc)
      local old = init
      if inc then init = init + inc end
      return old
    end
  end
  return unpack(funcs)
end

x1, x2, x3 = counters(1, 20, 300)
> =x1(1), x2(1), x3(1)
1       20      300
> =x1(-2), x2(-2), x3(-2)
2       21      301
> =x1(), x2(), x3()
0       19      299
>