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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With