Is metatable only helpful for OOP?

I was started for learning metatables and methamethods, is metatable only helpful for OOP? If not, what can I do with metatable and methamethods?

1 Like

Mmm, an interesting question, I still don’t know how to use metatables, I would like to see an answer from other developers

2 Likes

You can do anything you want with metatables and metamethods

Metatables and OOP are different things.

Please so some research before posting.

I was not mean that, there’s other methamethods like “__add, __newindex” and i want to know where can you use “Like anti exploit systems”

Just search on google, and you find resources.

__add is when you call + operator on a metatable.
Just find on google or dev forum there are many posts like this.

Some meta methods are useful as a type of pseudo listener. Such as the __index and __newindex metamethods. However, they are particularly useful in OOP though because it allows you to define custom logic behind operators for custom classes like you can do in a language like c# by default using operator overloading. They can be powerful tools that can streamline your development process, whether or not you’re using OOP.

1 Like

No, you can add more functionality to tables with them.
I like to imagine metaTables set as properties of tables.

If you have two tables and want to make your script look for the thing in the other one if it doesn’t find it in the first one, you can use the __index metamethod.

If this script can’t find the element in normalTable, it will look for it’s metaTable’s __index.
In our case, __index is set to another table so it will check that table.

There are many other metamethods that can be used similarly to this example.

1 Like

With __newindex for example, you can kinda make a .Changed event for tables.

newindex fires when a new element tries to be set, so we can’t use our main table.

__add fires whenever you are trying to add something to a table that has a metaTable.

I read somewhere that it’s expensive to set functions to metamethods, I’m not sure if that’s true, if anyone knows that, please reply to this.

2 Likes

Yeah I remember I read that somewhere too.

1 Like