Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can't index a metatable element?

Asked by
funyun 958 Moderation Voter
9 years ago

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

Log in to vote
4
Answered by 9 years ago

Please provide explanation with your answers. Simply posting code does not spread knowledge of integral scripting processes which helps people understand the logic and reasoning behind your 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

4
I swear you didn't have to do that in old Roblox. funyun 958 — 9y
5
Oh, I don't know o: XToonLinkX123 580 — 9y
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? adark 5487 — 9y
Ad

Answer this question