I understand metatables but I just need someone to clear this up for me

I just get confused how you set a metatable to a table, and put the index of the metatable as itself so when you index something that isn’t in the table it goes to the metatable, but I don’t really get what the metatable actually is because why doesn’t roblox just automatically check the metatable to see if they have it. And some people have said that roblox sees that the metatable is the metatable of table and then sees the index of metatable is metatable so THEN it looks in there, but did it not have to look in there to find the index of it?

I’m sorry, I’m struggling a bit trying to understand your question. Would you mind elaborating further? :slight_smile:

If this cleans anything up, the metatable is essentially just any ordinary table that has defined metamethods. It can be the table object itself even, or a separate one that specifies behavior.

local metamethods = {
__index = pathToSomeOtherThing;
}

local myTable = {1, 2, 3}

setmetatable(myTable, metamethods)

--//Alternatively,

local myTable = {1, 2, 3}

myTable.__index = pathToSomethingElse --//The metamethod is defined in the table itself.

setmetatable(myTable,  myTable)

So basically, when I have a table, and that table has a metatable. For example:

local table = {}
local metatable = {x = "blah"}
metatable.__index = metatable
setmetatable(table, metatable)
print(table.x)

This would obviously work and print blah, but when I print table.x, it obviously isn’t in that table right now what does roblox do? I’m pretty sure that it sees that metatable is the table’s metatable and looks inside of it and see’s that the __index is metatable, so it goes ahead and looks in metatable and woah its there, but when roblox goes through and sees the “__index” do they not see that x is obviously in the metatable? Like why do i have to set the index of a table to itself?

Roblox doing this basically just gives you flexibility: you can assign the “.__index” to any table you want.

For example, instead of always doing this:

local metatable = {x = "Hello there"}
metatable.__index = metatable

Roblox gives you the flexibility to do this:

local metatable = {}

local randomTable = {x = "Hello there"}
metatable.__index = randomTable 

In both examples above doing print(table.x) here will print “Hello there”