Search code examples
ooplualua-tablemetatable

What's difference between "t1.__index = t2" and "setmetatable(t1, {__index = t2})"?


I seen this things in others code, and if I understood correctly it should be used like this:

t1 = {}
t1.__index = t2 --1

function t1:new()
    local new = {}
    setmetatable(new, {__index = t1}) --2

    new.something = 0

    return new
end

But what they really do and why have different way of writing?


Solution

  • They are written differently because they do different things.

    t1 = {}
    t2 = {a = 20}
    meta = {__index = t2}
    setmetatable(t1, meta)
    print(t1.a) -- prints 20
    

    Note how there's 3 tables here: meta, the metatable, t2, which stores the key a and t1 which we want to set to look up missing keys in t2.

    The metatable only serves teh purpose of controlling the behavior of t1, but, to use less tables, people often use the fallback table (t2) as the metatable (meta) so it becomes something like

    t1 = {}
    t2_and_meta = {a = 20}
    t2_and_meta.__index = t2_and_meta
    setmetatable(t1, t2_and_meta)
    print(t1.a) -- prints 20