Search code examples
lualua-table

Detect all changes to a nested table in Lua


Assume I have a nested table like this:

local a = {
  b = {
    c = {
      d = 'e'
    }
  },
  f = {
    g = {
      h = {
        i = 'j'
      }
    }
  }
}

(Ignore the variable names, they're just placeholders)

So what I want to know is, how do I trigger a function everytime that table or any of its sub-tables are modified. For example, if I do a = { 'something' } or if I do a.b = { 'something' } or if I do a.b.c = { 'something' } and so on. Using the __newindex metamethod in a metatable that uses a proxy table I can only trigger the function on the second case. (eg: when I do a.b = { 'something' })

Is there a way to trigger it everytime any element of the nested table is modified? The reason I need it is because the table needs to cache the indices of certain values, so when a value is changed, I need to re-cache the table.

Your help is appreciated. Thanks in advance.


Solution

  • If you want to monitor assignments in nested tables, each table needs a __newindex metamethod.