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

Multiple __index Metamethods in a Metatable?

Asked by
Minifig77 190
9 years ago

So, I'm playing around with metatables, and on the Wiki, I learned this little trick:

local metatable= {
    __index = {value= true}
}
local regulartable = setmetatable({}, metatable)

print(regulartable.value)

Prints "true" in the output.

I wanted to see if I could put multiple __index metamethods in the same metatable, so, in essence, I could have multiple pseudo "properties" of a table. I tried this:

local metatable= {
    __index = {value= true},
    __index = {secondvalue = false}
}
local regulartable = setmetatable({}, metatable)

print(regulartable.secondvalue, regulartable.value)

I noticed that with the second value set, the first value would be nil. I tried a few other things, but they all showed up as incorrect on the syntax checker, so they aren't worth mentioning here.

How do I set multiple __index metamethods in a single metatable?

2 answers

Log in to vote
2
Answered by
Minifig77 190
9 years ago

With a few more minutes of playing around, I discovered how to do it. (Funny how it works out.) Basically, you do this:

local metatable= {
    __index = {value= true,
        secondaryvalue = false}
}
local regulartable = setmetatable({}, metatable)

print(regulartable.value, regulartable.secondaryvalue)

This would print: true false

This means that there is no need for multiple __index metamethods in a metatable.

Ad
Log in to vote
0
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

Minifig is correct, but the reason you can't set multiple __indexs is because the second definition replaces the first.

It's like trying to do this:

x = 1
x = 4

if x ~= 1 then
    print("Broken!!!")
end

Answer this question