I’ve looked at the documentation and there does not seem to be a metamethod for
table[index] = value
where table[index] already exists. I want to interrupt this from happening and maybe signal another script that this index was changed. Is there something I’m missing or does this metamethod not exist?
I do not want to write my own custom wrapper function.
So, based on my understanding, you’d like to fire a signal when an index with a non-nil value is modified. There really isn’t a dedicated metamethod.
You can opt for an empty proxy table that represents the real table. Then any attempts to access or modify the proxy are detected and the changes are applied to the real table.
local tbl = {}
local proxy = {}
setmetatable(proxy, {
__index = function(_, k)
return tbl[k]
end,
__newindex = function(_, k, v)
if tbl[k] ~= nil then
print(string.format("Modified existing key '%s' with value '%s'", k, v))
end
tbl[k] = v; return
end,
__iter = function(self)
return next, tbl
end,
})
proxy["key"] = "value"
proxy["key"] = "another value"
proxy["second key"] = "second value"
I had to add the iterator field to reroute the iteration to the real table. Proxy is empty.
Some downsides:
- Access is slightly slower compared to direct table access.
-
table.insert()
andtable.remove()
don’t invoke any metamethods in arrays (not including mixed tables).table[index] = value
is still observed.
The most straightforward way of course is to have a wrapper, essentially as simple as a function that accepts a value and decides what to do with it, and signaling that there was a request to add something to the table.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.