Can someone explain to me how metatables work?

I am so very confused on metatables, for example. Why the hell do we need to use it, how does it even work and what is a “metatable”?

Metatables contain metamethods, that then fire whenever you do something to a table you bound a metatable to.
They’re events basically, just for tables.

Say I have a dictionary like so:

local t = { This = 1, That = 2 }
setmetatable(t, {
    __index = function(t, i)
        print(i)
    end,
})

The __index metamethod fires when you try accessing the index of a table that doesn’t exist.
If you did something like t.Those, that table will recognize that Those doesn’t exist in t, and therefore you’ll get this in your output:

--> Those

There’s a ton of metamethods, but going through them will make this reply go on for miles.

The most prevalent use of metatables at the moment is for OOP.
There’s a couple of posts in DevForum that teaches you how to use metatables for OOP already, look them up.

1 Like