Metatables' problem

Hi. I am having a problem using metatables. The idea is a code it converts all tables in metatables hosted in an ancestor or main table. After many tests, I reached the objective, but only if the table is like this form:

setmetatable(tab, {}); --[[where]] tab = {"example" = {}}

I don’t like this form. I would like something like:

setmetatable(tab, {}); --[[where]] tab = {}

I tested something like that but it returns an error, and when I am using rawset() the code ‘skip’ the __newindex() function.

My code:

function getMethod(t)
    if typeof(t) ~= 'table' then return t end
    local metatable = setmetatable({tab = {}}, {
        __index = function(proxy, key)
            local result = rawget(proxy, "tab")
            if result then return result[key] else return end
        end,
        __newindex = function(proxy, key, value)
            local result = rawget(proxy, "tab")
            print("newindex", key, value)
            rawset(result, key, getMethod(value))
        end,
    })
    for key, value in pairs(t) do metatable[key] = value end
    return metatable
end

--> Examples

local tab = getMethod({
    name = "John",
    data = {"Apples", 4}
})

tab.name = "Steven"
tab.data= {"Oranges", 6}

tab.data = {}
tab.data[1] = "Bananas"
tab.data[2] = 9

tab.coins = 40

print(tab)

Thanks! :slight_smile:

1 Like

Hi there is is how i setup a metatable and works 100% fine

local Race = {}
Race.__index = Race

function Race.new(RaceName,player)
    local self = setmetatable({},Race)
    self.player = player
    self.RaceName = RaceName
    return self
end

return Race

Good Video On self: What is the self keyword in Lua? - Roblox Studio - YouTube

1 Like

I’m not really sure what you’re trying to do here exactly, could you clarify a bit?

:slight_smile:

1 Like

Hello! It’s a table it fires the function __newindex when a value from the table changes (like Instance.Changed). If some value of the main table is another table, fires the same function too. It works but only if the ‘main table’ is children from another table (look the line when I define the metatable: “{tab = {}}”). This is a problem because when I gonna manipulate the table looks ugly and unprofessional.

For example, if I convert the next table:

meta = {name = "John", apples = {nom = 40, price = 6}}

It will be like:

meta = {tab = {name = "John", apples = {tab = {nom = 40, price = 6}}}}

Thank you!