local t = setmetatable({}, {
__newindex = function(self, index, value)
rawset(self, index, value)
if #self == 1 then
print("index is 1")
elseif #self == 2 then
print("index is 2")
end
end,
__index = function(self, index)
if self[index] == nil then
rawget(self, index)
print("an index was removed")
end
end})
for i = 1, 2 do
t[#t + 1] = "yes"
end
wait(1)
for i, v in pairs(t) do
t[i] = nil
print(v)
end
Title basically explains my problem, I’m testing how to detect when a value gets removed from a table using metatables.
Here is a quick solution. Basically whenever the metatable is indexed or an index is changed, it will update a “data” table, and you can check value changes then and there.
local Meta
local Data = {}
Meta = {
__index = function(self, index)
return Data[index]
end,
__newindex = function(self, index, value)
Data[index] = value
if value == nil then
print("Value was set to nil")
end
end,
}
local Table = setmetatable({}, Meta)
Table[1] = "asd"
wait(5)
Table[1] = nil -- "Value was set to nil" will be printed to console.
sort of, i still want to keep the code in the __newindex as is, cause that detects when there is 2 values in there to start an event. is there a way to integrate that with your code?