当前位置: 动力学知识库 > 问答 > 编程问答 >

lua - Whats the usage of metatables without metamethods?

问题描述:

I started learning Prototype-based programming in Lua. I wonder what's the usage of metatables without metamethods. There is a line in example below self.__index = self when I remove this line somevalue is not visible in my new object this is normal because I didn't use the metamethod __index. What's the usage of metatables then - to use metamethods only? Sorry for trivial question but this is really interesting, I know I can use getmetatable to check the metatable of some object. I need simple answer: There is no usage without metamethods or there is(if yes then what).

-- Example taken from the official documentation.

Account = { somevalue = 1 }

function Account:new (o)

o = o or {} -- create object if user does not provide one

setmetatable(o, self)

--self.__index = self

return o

end

a = Account:new()

print(a.somevalue) -- nil, so I can't use any features of the metatable till I use some metamethod?

网友答案:

By definition, metatables store metamethods. This does not mean that a metatable has to store only metamethods; several libraries use themselves as metatables.

A metatable is an ordinary Lua table. It only becomes the metatable of an object when you call setmetatable with it as its second argument.

网友答案:

You can also make keys or values or both weak with the __mode metatable key, which takes a string value and not a function (method)

Most metamethods are explained here:

  • Lua Manual: Metatables and Metamethods

Some Lua API functions also test for specific meta methods, like

  • __pairs - for pairs()
  • __ipairs - for ipairs()
  • __tostring - called by the tostring() function
  • __gc - for garbage collection
  • __metatable - read by the set/getmetatable functions (also a value)

If you search the manual file for the specific name including __ you will find the full definition and explanation, no use in repeating it here.

网友答案:

Well, yes, metatables store the metamethods of the object, and that's what they're used for, at least I haven't seen any other usecase.

分享给朋友:
您可能感兴趣的文章:
随机阅读: