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!