lua-users home
lua-l archive

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



On 25-Sep-05, at 11:00 AM, Enrico Tassi wrote:

What should we expect from this code?

x = 1
function f()
  x = x + 1
  return x
end

a,b,a = f(), f(), f()
print(a,b,x)

I checked a bit the Lua 5.0.2 manual and there is no clarification,
except for the fact that f() is called 3 times.

The result of the execution is 2,3,4.
I think there are 2 possibilities:
- after the f() calculation assignments are performed from the right
  to the left
- assignments are performed from the left to the right but there is a
  check for duplicate variable name

I guess the first.

As it happens, the assignments are performed right to left. But in my opinion, you should not rely on that fact, since it is unspecified in the manual.

In any case... isn't this a good place to generate an error? Is this
check considered too heavy or not so interesting?

There is no way in general to detect that two lvalues are "the same". Consider:


function g(x) return math.min(x, 2) end
a = {}
for i = 1, 10 do
  a[g(i)], a[g(i+1)] = f(), f()
end


On the other hand, the environment table might have a __newindex metamethod which made the assignments "different". Here is a dumb example:

do
  local function show(t)
    local tmp = {}
    for v in pairs(t) do table.insert(tmp, v) end
    table.sort(tmp)
    return table.concat(tmp, " | ")
  end
  local showmeta = {__tostring = show}

  local envmeta = {}
  local env = {}
  function envmeta:__index(k) return env[k] end
  function envmeta:__newindex(k, v)
    if v == nil then
      env[k] = nil
    else
      local vals = env[k] or setmetatable({}, showmeta)
      vals[v] = true
      env[k] = vals
    end
  end
  setmetatable(getfenv(), envmeta)
end

> a, b, a = 1, 2, 3
> =a
1 | 3
> =b
2
> =a[2]
nil
> =b[2]
true