[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Overloading the '=' operator for a table
- From: Matthew Paul Del Buono <delbu9c1@...>
- Date: Tue, 18 Nov 2008 13:02:57 -0500 (EST)
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.
Good luck,
-- Matthew P. Del Buono