View Single Post
05-15-19, 06:56 AM   #2
Vlad
A Molten Giant
 
Vlad's Avatar
AddOn Author - Click to view addons
Join Date: Dec 2005
Posts: 793
You can use metatable to achieve inheritance, which in return can be used to create some sort of class hierarchy even when lua itself doesn't have the syntax or concept of class or inheritance, you can manipulate a table to behave vastly different than a regular table when using metatables.

It really depends on how you implement it, but most cases such metatables provide some sort of syntactic sugar so to speak. Like you mentioned yourself you could in your example just call a function on the table instead of using metatable to define a custom _call function and so on.

The last point worth mentioning is that even if via metatables you can achieve a lot of funky behavior, in the end I recommend to consider what if someone else read this code, will they understand what it does?

One way you can use metatables to make it easier to read and maybe easier to update your code if you use it a lot of places, is to for example make a factory that produces and returns you a 3d vector representation, in lua it would be a table. You could use metatable on this to add basic math operations and code in how it would then modify the table given your input. It would make it clean to write local newvector = vector1 + vector2 and you would know to modify the metatable in your definition file for vectors if you want to expand functionality.

Then again you could also approach this and simply do local newvector = vector.add(vector1, vector2) where you have a table vector with all the operations that you need in it.

TLDR; metatables add syntactic sugar but are not mandatory in any way.

Just a link to the official documentation. https://www.lua.org/pil/13.html
__________________
Profile: Curse | Wowhead
  Reply With Quote