lua-users home
lua-l archive

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


In the __index and __newindex you are getting/setting the fields of
_eq, not those of _eq.chain*.
check

print(eq.chan1.chan2)

even before setting anytihg in the tables, just after the setmetatable
statements.

You should make the metatable aware of which mirror it should use. I
would try a generator function approach. It would make easy to do it
all automatically with a metatable for eq.

It would work like this

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

setmetatable(eq.chan1, get_mt_mirror(_eq.chan1))
print(eq.chan1.op3)

cheers,

--mi

On 14/07/07, Merick <Merick_TeVaran@comcast.net> wrote:
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)