Hey there, I’m currently messing with metatables and datas, you can have a look at my constructor here:
function constructMetatbl(originalTbl, callback)
local changedEvent, events
local proxy = setmetatable({}, {
__index = function(self, key)
return rawget(originalTbl, key)
end,
__newindex = function(self, key, v)
if callback then
callback(key, v)
end
if changedEvent and events then
changedEvent:Fire(key, v)
if events[key] then
for i, bindable in pairs(events[key]) do
bindable:Fire(v)
end
end
end
return rawset(originalTbl, key, v)
end,
})
for i, v in pairs(originalTbl) do
if type(v) == "table" then
rawset(proxy, i, constructMetatbl(v, callback))
end
end
changedEvent, events = addChangedEvent(proxy)
return proxy
end
My first question is is it possible to loop through a metatable ? Because when I loop the whole table it doesn’t print out anything because there’s technically nothing in a metatable.
Second of all,
for i, v in pairs(originalTbl) do
if type(v) == "table" then
rawset(proxy, i, constructMetatbl(v, callback))
end
end
This recursion loops through the original table and construct another metatable if the value is a table, then I set that metatable to the prior table. However, doing so would restrain me from calling that particular key that was assigned to because it already exists, so the __index
metamethod wouldn’t be called.
Lets say this is my metatable:
local metatable = { -- first metatable
key = {
-- another metatable, lets say it has a key named "a" with a value of "b"
}
}
If I was to call metatable.key
, it would print out nil, but if it was metatable.key.a
it would print out "b"
.
I have tried altering the smaller metatable parent to the orignal table like so rawset(originalTbl, i, constructMetatbl(v, callback))
. But this just seems to facilitate more errors, is there any workarounds to this problem ?
Any help is appreciated profusely!