Detecting metatable values change?

I am trying to make a metatable that will detect when a value is changed. Is it possible?

This is what I have wrote so far but the __newindex does not run when a value is changed inside of a table

local dataMetatable = {
	__index = function(t, userId)
		local newEntry = {}
		rawset(t, userId, newEntry)
		return newEntry
	end,
	__newindex = function(t, userId, value)
		if type(value) == 'table' then
			local playerMeta = {
				__newindex = function(innerTable, key, value2)
					print('key = '.. key)
					if key == 'Diamonds' then
						print('Diamonds value changed for user' .. userId.. ': ' .. tostring(value2))
						UpdateDiamondLeaderstats(userId)
					elseif key == 'Level' then
						print('Level value changed for user' .. userId.. ': ' .. tostring(value2))
						UpdateLevelLeaderstats(userId)
					end
					
					rawset(innerTable, key, value2)
				end,
			}
			setmetatable(value, playerMeta)
		end
		rawset(t, userId, value)
	end,
}
playerData.PlayersData = setmetatable(playerDataTable, dataMetatable)

I have been looking at old posts and they dont seem to really help. I have also seen some things saying that this is not possible. I dont want to remove the table and add it back with the new value either.

There’s no metamethod that really can detect a change to a key/index -value pair in a normal table. One thing you could try doing is having the normal table blank, and the actual values stored in a separate table which the __index metamethod points to. Also hook __newindex up to redirect requests to that table. Then, you can check when the value is changed through the __newindex metamethod on the original table, since it will always fire.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.