[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: how to handle # operator for proxy tables?
- From: Valerio Schiavoni <valerio.schiavoni@...>
- Date: Tue, 8 Jun 2010 16:40:30 +0200
So, the way I did it is using newproxy, but is there something safer to do ?
proxytable = function (orig)
local p = newproxy(true) -- create proxy object with new metatable
getmetatable(p).__len = function() return #orig end
getmetatable(p).__newindex=function(p,k,v)
rawset(orig,k,v);
if (k==1) then
print("do something")
end
end
getmetatable(p).__pairs = function(t) return pairs(orig)end
return p
end
On Tue, Jun 8, 2010 at 4:18 PM, Valerio Schiavoni
<valerio.schiavoni@gmail.com> wrote:
> hello,
> i use proxy tables to catch modifications on 1st elements of a table:
>
> proxytable = function ( orig )
> return setmetatable({},
> {
> __index=orig,
> __newindex=function(t,k,v)
> rawset(orig,k,v);
> if (k==1) then
> print("do something")
> end
> end,
> __len=function(t) return #orig end,
> __pairs = function(t) return pairs(orig)end })
> end
>
> t={1,2,3,4}
> print(#t)
> t=proxytable(t)
> print(#t)
>
> The problem is that the i was expecting the 2nd call to #t to return 0.
> How can I get around this?
>
> It seems Lua5.2 will handle this:
> http://www.batbytes.com/luafaq/#T8.2.5, but for now I'm stuck with
> 5.1.4.
>
> Thanks
> Valerio
>