[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Order of metatable accesses
- From: "Joseph C. Sible" <josephcsible@...>
- Date: Mon, 16 Nov 2020 16:49:55 -0500
Consider this Lua program:
local x = {
a = setmetatable({}, {__newindex = function(t, k, v)
print('setting a.' .. k)
end}),
b = setmetatable({}, {__newindex = function(t, k, v)
print('setting b.' .. k)
end}),
c = setmetatable({}, {__index = function(t, k)
print('getting c.' .. k)
end}),
d = setmetatable({}, {__index = function(t, k)
print('getting d.' .. k)
end})
}
setmetatable(_G, {__index = function(t, k)
print('getting ' .. k)
return x[k]
end})
a.foo, b.bar = c.baz, d.qux
When I run it, it prints this:
getting a
getting b
getting c
getting c.baz
getting d
getting d.qux
setting b.bar
setting a.foo
How much of the ordering of these metatable accesses is guaranteed? It
looks like it does all of the __index calls left-to-right and then all
of the __newindex calls right-to-left. But the only thing I see in the
manual is "The assignment statement first evaluates all its
expressions and only then the assignments are performed." Should the
manual make a stronger statement, or is what it says all that's
guaranteed and the other ordering I noticed just an implementation
detail?
Joseph C. Sible