I'm getting into some more advanced scripting and I want to know more about metatables. Like how to use them, and what are they used for?
A metatable is not a table within a table. If it were, this would be valid:
local t = { m = {} }
Is that a metatable? No, it's just a simple dictionary.
A metatable describes what should happen when the table is under certain conditions. I think of them almost like events (although they're not events) because they do A when B happens.
Metamethods are functions in the metatable that fire when something happens. Again, I think of them as similar to events.
Now for an actual example. There's a whole list of metamethods on the wiki that all fire when different things happen. One of them is __call
. This metamethod will fire when the table is called like a function. Take a look:
local list = {} local metatable = { __call = function(list, parameter) print(parameter) end } setmetatable(list, metatable) list("Hello, world!")
Pretty cool, eh? Normally, if you tried to call a table, you would just get an error.
An important thing to remember is that __call
and other metatmethods have two underscores. This is easy to forget.
This is a helpful post on this website on the topic.