Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Can't index a metatable element?

One of the first things that people will teach you about metatables is that you can put elements in the metatable that aren't in the table. Then, when you try to index an element in the table that isn't there, the script looks for that element in the metatable. This is a concept that I'm trying to experiment with:

t = {}
mt = {hi = "hi"}

setmetatable(t, mt)

print(t.hi)

This printed "nil", which it should've if the metatable wasn't attached. The metatable was attached though. What am I doing wrong here?

1 answer

✓ Accepted answer

Thats what you forgot here it was the metamethod named as "__index", that Fires when table[index] is indexed, if table[index] is nil. Can also be set to a table, in which case that table will be indexed.<--This part is in Roblox wiki, for more information you can look here .

t = {} --The table here for mixing with the metatable
mt = {__index = {hi = "hi"}} -- ops, you forgot to declare the metamethod

setmetatable(t, mt) -- mixing the table with the metatable.

print(t.hi) --Run the table as a print

3 comments

4

I swear you didn't have to do that in old Roblox.

5

Oh, I don't know o:

1

If you were using metatables in an older version of ROBLOX, you'd still have to actually use metamethods for it to work. Are you thinking about the change to _G?

This discussion is preserved as it was. New answers, comments, and votes are closed.