Detecting changes made to one particular nested table

Hello, I am looking to detect changes made to one particular nested table using metamethods.

For example, how would I only detect changes made to the value in table2 below?

local mainTable = {table1 = {value = 0}, table2 = {value = 0}}

Each table has its own metatable, so just only setmetatable() on mainTable.table2

Indeed, that’s what I had been doing, yet for some reason it just wouldn’t work. I started fresh and seem to have things functioning properly now. It might’ve been some other syntax error.

The working code for anyone that’s interested in the future:

local mainTable = {table1 = {value = 0}, table2 = {value = 0}}
local table2 = mainTable.table2

local metaTable = {
	__newindex = function (_, key, value)
		print("Updating " .. tostring(key) .. " to " .. tostring(value))
		table2[key] = value
	end
}

setmetatable(mainTable, metaTable)

mainTable.value = 1
1 Like

__newindex, as the name suggests, only triggers if someone is adding a new key to the table.

You can abuse this by creating a proxy table so that all assignments and “reassignments” are actually always new indexes into a proxy table. I describe the technique in the second half of this post:

However, consider my suggestion in the first half of that post: don’t screw around with metatables—just use methods to change the values you care about and do any side effects in those methods.

2 Likes

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