lua-users home
lua-l archive

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




On 27/01/16 03:04 PM, Stephan Hennig wrote:
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.
An access TO a metamethod is raw. The access TO a metamethod is what you use to get to the metamethod.

__pairs for example, calls the value using __call.

The access to a metamethod is provided through the metatable. The access of a metamethod is provided through the metamethod 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


--
Disclaimer: these emails may be made public at any given time, with or without reason. If you don't agree with this, DO NOT REPLY.