There's a method where you'd be doing something like this to the original table.
function setproxy(t)
new_t = {proxy = t}
setmetatable(new_t, mt)
return new_t
end
However, if you'd be printing out t
, you'd get this:
t["proxy"]
.
So I was wondering how to do the nested logging, in this fashion:
local Settings = {}
Settings.example = "Value"
local proxyTable = setmetatable({}, {
__index = Settings,
__newindex = function(t, k, v)
print(t, k, v)
Settings[k] = v
end,
})
proxyTable.example = "value"
With the exception that it supports nesting as well.
It can be a pain to figure out what is going on with this complexity.
So far I had this approach, but I am not sure if it's correct:
local table1 = {
table2 = {}
}
local function newProxy(tbl)
local mt = {}
mt.__index = tbl
mt.__newindex = function(t, k, v)
print(t, k, v)
if (type(v) == "table") then
v = newProxy(v)
end
rawset(t,k,v)
end
local newProxy = setmetatable(tbl, mt)
return newProxy
end
local proxyTable = setmetatable({},
{
__index = table1,
__newindex = function(t, k, v)
print(t, k, v)
if (type(v) == "table") then
v = newProxy(v)
end
rawset(t,k,v)
end,
})
for k,v in pairs(table1) do
if (type(v) == "table") then
v = newProxy(v)
end
rawset(proxyTable, k, v)
end
proxyTable.table2.a = {val = "value"}
proxyTable.table2.a.b = {a="a"}
proxyTable.table2.a.b.c = "hi"
for k,v in pairs(proxyTable) do
print(k,v)
end
point of the a.val
is to test cases, because when I tried to do this, a would have reset back to {}
if I created a table inside of it.
And it was all depending on local newProxy = setmetatable(tbl, mt)
. If I'd set it to local newProxy = setmetatable({}, mt), I'd reset proxyTable.table2.a = {val = "value"}
if I created proxyTable.table2.a.b = {a="a"}
That's my current approach. Maybe it's even the correct way, but I don't know.
What I need to know is, whether my approach is still a proxy, or whether by doing this newProxy = setmetatable(tbl, mt)
if I already broke the purpose.
Because I believe I only need one proxy. And seen that proxyTable, is a proxy for table1. I believe it's already done.