What is metatables?

  1. What do you want to achieve? I want to learn about metatables. I have tried searching it up on youtube but no luck. Can you help?
  2. What solutions have you tried so far? Youtube

research before asking

Metatables, are magic table functions that do more to a table than before, or change the behavior of a table, every table in lua has it’s own metatable.

Suppose we have two tables, t and tm, and I want to set tm to t, I can use the setmetatable() function to do so,

local t = {}
local tm = {}

local mt = setmetatable(t, tm) --> tm is now a part of t's metatable
print(getmetatable(mt)) --> some hexadecimal table

Now, tm is apart of t! It sets one metatable to another, forging each other.

Well, those are metatables, metamethods are methods used by these metatables for particular reasons, indexing a table, readonly table, adding two tables, etc, suppose we have mt, a metatable variable,

local mt = setmetatable({1, 2, 3}, {
    __index = function(self, k) --> self is our table, 'k' is our key, so (table, key)
        print('indexing a nil key')
    end
})

__index is fired when you call mt[] on a index that’s nil, calling print(mt[1]) will print 1, and calling print(mt[4]) will print that statement above.

__newindex is fired when a new index is being made, such as mt[4] = 'key', i.e,

local mt = setmetatable({1, 2, 3}, {
    __newindex = function(self, k, v) --> 'v' is our value, so (table, table-key, key-value)
       rawset(self, k, v) --> IIRC self[k] = v would cause a 'C stack overflow', hence avoid doing that
        --> rawset is a function that is similar to above, yet more reliable for metamethods, it doesn't invoke any metamethod as self[k] = v would, causing that stack overflow.
        --> first arg: table, second arg: any but nil, third arg: any lua variable
    end
})

Now, saying mt[4] = 'key' would set our tables 4th index as ‘key’, you can also set the other key-values as well, from 1 → max number of keys in your table.

rawset() sets a key to a table, hence self, and that ‘v’, our value is set to that key on the table, rawget() to get the tables’ key, I usually prefer this whenever I call __index in my metatables, they don’t provoke any metamethods at all.

There are some resources you should look at for more information about metatables and metamethods, probably missed some more information or errors on explanations of each,

Programming in Lua : 13,
All you need to know about Metatables and Metamethods,
Metatables | Roblox Creator Documentation

1 Like