lua-users home
lua-l archive

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


>     The closest you can do is use the __newindex
>     metamethod. This isn't exactly what you've asked
>     for, though you might be able to work it the way
>     you want it to.
>
>     > t = {1,2,3}; setmetatable(t, {__newindex =
>     function(t,k,v) print(t,k,v) rawset(t,k,v) end});
>     > t[5] = 4;
>     table: 000000000068BEC0 5       4
>     > t[5] = 5;
>     > t[3] = 2;
>
>     Take note that you only get __newindex called when
>     it is new, by design. You can work around that by
>     using __index as well, if you need to:
>
>     > t = setmetatable({}, {__index = {1,2,3},
>     __newindex = function(t,k,v)
>     >> print(t,k,v)
>     >> getmetatable(t).__index[k]=v;
>     >> end});
>     > t[5] = 4;
>     table: 000000000068BF60 5       4
>     > t[5] = 5;
>     table: 000000000068BF60 5       5
>     > t[3] = 2;
>     table: 000000000068BF60 3       2
>
>     But be careful with this as well, as you will lose
>     the ability to use pairs() and ipairs() on the
>     table without extra work.
>
>   Thanks this is a start, but how could I get pairs()
>   and ipairs() to work again?
>   Thanks.
>   --
>   Regards,
>   Ryan

The easiest thing to do that I can think of will be to hook pairs() and ipairs() to look into __index as well. What I would probably do personally would be to write a function that actually generates the iterator, rather than relying on pairs() or ipairs(), but that really is dependent upon the application.

On a side note, I had thought I heard some discussion a while ago about something like a __next or __pairs metamethod potentially possible in a future version; that would be the optimum solution.

Regards,
-- Matthew P. Del Buono