Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the usage of metatables without metamethods?

Tags:

lua

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?
like image 326
deepspace Avatar asked Jun 26 '13 18:06

deepspace


3 Answers

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.

like image 157
lhf Avatar answered Oct 17 '22 18:10

lhf


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.

like image 34
dualed Avatar answered Oct 17 '22 17:10

dualed


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.

like image 25
Bartek Banachewicz Avatar answered Oct 17 '22 18:10

Bartek Banachewicz