0

Hello everyone!

I've been studying metamethods and I realized something strange!

I already know all the metamethods presented in the Lua documentation as __add, __index, __newindex, etc... But I see around in forums and in questions around here people using metamethods like __ev , __close, __group, and I have never seen anywhere else these metamethods be used or exist in any documentation.

My question is, these metamethods exists? and if not, how are they created? and why people create this metamethods?

anyway, thanks for the attention

Vinni Marcon
  • 606
  • 1
  • 4
  • 18

1 Answers1

1

These are custom metamethods and have special purpose in specific project or framework.

Metamethods are used to extend functionality of table or userdata. These are most usable to achieve OOP behavior.

Some programmers add custom metatables and metamethods for internal purpose and better readability, such as __super, __extend, __inherit. In most cases such metadata are used from standard metamethods as __index, __call, ... or from routine methods to cleanup objects, error handling and so on.

For example __close could be used with connection or file objects to manage them in predictible way, __gc can't be trusted for this purpose.

Example of __group usage: Lua metatables and metamethod - How to call a different member function

Darius
  • 1,060
  • 2
  • 6
  • 17
  • 1
    Extending is the magic what you can do and dont forget the metamethod ```__metatable``` to protect the extensions. Look at a string ```_VERSION``` for example has the __index method as table filled up with ```string``` functions. So with every string you can do the magic: ```print(_VERSION:rep(50))``` The question is: Why dont have the datatype table and integer no metamethods? – koyaanisqatsi Aug 24 '20 at 18:37