Trying to detect when an index is removed from a table, but when setting the value to nil, it doesn't work and doesn't fire the __index event

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.

1 Like

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.

Is this what you were looking for?

1 Like

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?

You should be fine to just add it with the __newindex metamethod on my metatable.

Would I need to use rawget on the __index metamethod because I am using table.remove?

1 Like