[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: [manual] chaining metamethods
- From: Stephan Hennig <sh-list@...>
- Date: Wed, 27 Jan 2016 18:04:52 +0100
Hi,
the sentence
Note that queries for metamethods are always raw; the access
to a metamethod does not invoke other metamethods.
, new to the Lua 5.3 manual, is misleading. The second half of the
sentence can be interpreted as: An access to a metamethod, which can be
a table as described later, will not respect that table's metatable.
Which is not true and which would make chaining metamethods impossible.
What does not invoke other metamethods is retrieving metamethods from
the metatable itself.
-- A custom __gc metamethod that prints something on the screen.
local function my__gc(t)
print(tostring(t), ' is garbage collected.')
end
-- Watch garbage collection of a table via __gc metamethod.
local t = {}
local mt = { __gc = my__gc }
setmetatable(t, mt)
print(t)
t = nil
collectgarbage()
-- Try again with an empty metatable. Does Lua respect the
-- metatable's metatable?
local t = {}
local mt = {}
local mtmt = { __index = { __gc = my__gc } }
setmetatable(mt, mtmt)
setmetatable(t, mt)
print(t)
t = nil
collectgarbage()
-- OK, Lua is disrespectful (to metatables).
I'd suggest something along these lines:
Note that queries for metamethods are always raw; when
looking-up metamethods, Lua doesn't consider a metatable's
metatable. Lua considers metatables of metamethods, though.
In fact, chaining metamethods is at the heart of many
approaches to object-oriented programming in Lua.
Best regards,
Stephan Hennig