5

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?
4

3 回答 3

4

根据定义,元表存储元方法。这并不意味着元表必须存储元方法;几个库将自己用作元表。

元表是一个普通的 Lua 表。setmetatable只有当您将其作为第二个参数调用时,它才会成为对象的元表。

于 2013-06-26T18:48:06.667 回答
3

您还可以使用__modemetatable 键使键或值或两者都变弱,它采用字符串值而不是函数(方法)

大多数元方法在这里解释:

一些 Lua API 函数也会测试特定的元方法,比如

  • __pairs- 对于对()
  • __ipairs- 对于 ipairs()
  • __tostring- 由 tostring() 函数调用
  • __gc- 用于垃圾收集
  • __metatable- 由 set/getmetatable 函数读取(也是一个值)

如果您在手册文件中搜索特定名称,包括__您将找到完整的定义和解释,此处不再重复。

于 2013-06-26T20:06:24.370 回答
1

嗯,是的,元表存储对象的元方法,这就是它们的用途,至少我没有看到任何其他用例。

于 2013-06-26T18:47:00.883 回答