2

The __index of the table originally set a meta table, and the actual access is to the function under this meta table.

setmetatable(flatTbl, {__index = metaTbl}

I want to access the function of the same name of the meta table when the field of the table is not accessible, but I have used two methods without success

function FlatBufferTools:SetMeta(flatTbl)
    setmetatable(flatTbl, {
        __index = function(tbl, key)
            metaTbl = getmetatable(tbl).__index
            return metaTbl[key](metaTbl)
        end
    })
end

function FlatBufferTools:SetMeta2(flatTbl)
    metaTbl = getmetatable(flatTbl).__index
    setmetatable(metaTbl, {
        __index = function(tbl, key)
            return tbl[key](tbl)
        end
    })
end

The first method is to reset the __index of the table, but the metaTbl that i get is a function

The second method is to set __index to the table's meta table(metaTbl), but the setmetatable function skips it

I checked the metaTbl and there is no __metatable

Rider
  • 91
  • 4

2 Answers2

1

I want to access the function of the same name of the meta table when the field of the table is not accessible

local meta = { myFunc = function () print("metatable here") end }
meta.__index = meta

local a = setmetatable({}, meta)
a.myFunc()

a.myFunc is nil so you'll call meta.myFunc

Piglet
  • 27,501
  • 3
  • 20
  • 43
0

You know the table library?
Lets make the table functions "not accessible" to a and raise them to methods...

> a = setmetatable({}, {__index = table})
> for i = 1, 10 do a:insert(i) end
> print(a:concat('\n'))
1
2
3
4
5
6
7
8
9
10
>
koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15