lua-users home
lua-l archive

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


The documentation for multiple assignment (section "3.3.3 –
Assignment" in the manual) doesn't mention the fact the assignment is
*not* carried out in order. That is, that the assignment isn't carried
out from left to right. E.g., given the code:

    t.one, t.two = 1, 2

then the programmer is wrong to assume that t.one is assigned before t.two.

This matters when the assignment triggers a function (i.e., when 't'
has a metatable with __newindex) and when the order of calling the
functions matter.

Here's complete code to demonstrate the problem:

    local t = setmetatable({}, {
      __newindex = function(self, k, v)
        print("Assigning to key " .. k)
      end,
    })

    t.one, t.two = 1, 2

Running the this program produces this surprising output:

    Assigning to key two
    Assigning to key one

BTW, is it guaranteed that the assignment order goes from RIGHT to
LEFT (I verified this in Lua 5.1, 5.2, 5.3, LuaJIT), or is it
"undefined behavior"?