lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I'd like to set up a table with a number of subtables, with each subtable holding 5 elements. When one of the elements in a subtable is changed (either individually or by setting the entire subtable as equal to another table), I want it to automatically call a function using the elements of that subtable as it's arguments. From the tutorials I gather that the way to do this is by using a proxy table and setting the __index and __newindex metamethods to access the real table, but although I kinda understand how to use it for a single table, my test script to use it with nested tables doesn't work:

_eq = {
  chan1 = {op1 = 1,op2 = 2,op3 = 3,op4 = 4,op5 = 5},
  chan2 = {op1 = 1,op2 = 2,op3 = 3,op4 = 4,op5 = 5},
  chan3 = {op1 = 1,op2 = 2,op3 = 3,op4 = 4,op5 = 5}
  }

eq = {
  chan1 = {},
  chan2 = {},
  chan3 = {},
  }

local mt = {
  __index = function(t,k)
      print("index",t,k)
      return _eq[k]
  end,
    __newindex = function(t,k,v)
      print("newindex",t,k,v)
      _eq[k] = v
  end
  }


setmetatable(eq.chan1, mt)
setmetatable(eq.chan2, mt)
setmetatable(eq.chan3, mt)

print(eq.chan1.op1)
print(eq.chan2.op1)
print(eq.chan3.op1)
print("")
eq.chan1.op1 = 5
eq.chan2.op1 = 6
eq.chan3.op1 = 7
print("")
print(eq.chan1.op1)
print(eq.chan2.op1)
print(eq.chan3.op1)