Trouble understanding how to use metatables

So I was reading the metatables article on the dev hub and I got pretty confused, from what I understood setmetatable basically attaches two tables. So I made a script to test it out:

local Table1 = {1, 2, 3}
local Table2 = {4, 5, 6}
setmetatable(Table1, Table2)
print(getmetatable(Table1)[4])

This printed nil, so I’m guessing I was just doing this completely wrong.

Yes, because you’re getting the position 4 which doesn’t exist in either of them. Both the tables are only 3 elements long. If you want to get “4” then, you have to use 1 as the position.

print(getmetatable(Table1)[1])
1 Like

Oooooh I get it now, thanks!

1 Like

If what you’re hoping to do is add extra data to your table, then you should be using the index metamethod. A metatable shouldn’t really include anything except metamethods. So in this case, you should be using Table2 as the __index.

local Table1 = {1, 2, 3}
local Table2 = {4, 5, 6}
setmetatable(Table1, {__index = Table2})

In this case though, the index of 4 is still nil in both tables. You could change __index so that it works with additional indices but that seems like silly and pointless overhead.

1 Like