hgiesel
hgiesel

Reputation: 5648

Lua setting __index in metatable

I try to do basic inheritance in Lua and I don't quite understand why the following doesn't index the table mt.prototype in my call to print().

local x = {}

mt = {}

mt.prototype = {
  value = 5,
}

mt = {
  __index = function (table, key)
    return mt.prototype[key]
  end,
}

setmetatable(x, mt)

print(x.value)

It says that mt.prototype doesn't exist, however I don't understand why.

Upvotes: 2

Views: 414

Answers (1)

Oka
Oka

Reputation: 26355

You're overwriting mt, on line 9, when you reassign to it. This destroys the prototype field.

Don't complicate things, if it's your first try with this stuff. Your __index function would do the same thing that letting __index = tbl would handle.

local main_table = {}

local proto_table = {
    value = 5
}

setmetatable(main_table, { __index = proto_table })

print(main_table.value)

If you want the slightly more complicated setup, study this:

local main_table = {}

local meta_table = {
    prototype = {
        value = 5
    }
}

meta_table.__index = meta_table.prototype

setmetatable(main_table, meta_table)

print(main_table.value)

Note that the LHS of assignment is not fully quantified during RHS evaluation, that's why the __index must be set on a separate line.

Upvotes: 3

Related Questions