Set the meta table for the lua meta table

113 Views Asked by At

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

2

There are 2 best solutions below

0
Piglet On

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

0
koyaanisqatsi On

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
>