Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Could someone explain to me what metatables are and how to use them?

Asked by 8 years ago

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?

1 answer

Log in to vote
2
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
8 years ago

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.

0
WOOT GO PERCI1!! EzraNehemiah_TF2 3552 — 8y
0
thank you, all great and powerful perci HungryJaffer 1246 — 8y
0
oyus i should start my own cult ;p Perci1 4988 — 8y
Ad

Answer this question