Metatables Query

I’ve watched plenty of videos on metatables but im still confused as to what they are actually used for and what their proper use case is.

I realise its something to do with if another table is requested and its empty you can have a default per to say.

Please can someone explain metatables and what they are actually used for?

They’re useful for different purposes, many to do with OOP principles.
__index allows for inheritance (by searching other tables, you can extend it to search other tables for inheriting form multiple objects). It also has uses for access control in being used on a gateway table to block/control access to another table.

The mathematical ones __add, __div etc. are useful if you’re making custom objects which you want to apply mathematical principles by just using the standard operator symbols inline in your code. e.g. if you were implementing your own version of Vector2 you could now do table1 + table2 and can script __add to give table3 rather than having to do table1.add(table2).

__mode is useful for weak tables, which are used for modules. If you have a module which makes a table, and you want to store state information which isn’t directly accessible to a script using the module. For example if you again implemented a custom Vector2 class, but on every 4th addition it multiplied the value, you could store the vector2 table object as the key to a weak table, and the number of additions as a value to check when it is time to do the multiplication.

I use __call as a way to start services in module scripts which I want other modules to be able to access but not run the service code. e.g. module = require(script.Parent) to use the module and require(script.Parent)() to start it as a service from another script. There will be other uses, and really I think it is down to your creativity how you wish to use the metamethods.


Okay i see, so it just allows you to make tables stronger, detect changes in them, add them together etc

I’m not sure what you mean by stronger (as could be confused with the terminology of a weak table), but it allows you to use them in much more expressive ways, yes.

Yeah thats what i meant. Thank you