Anyone have a handy description of newproxy() function?
Or maybe care to submit a snippet for the Cookbook?
Thanks,
Alexander.
It's been taken out of Lua 5.2; is it worth talking about?
--
- Patrick Donnelly
It is — Lua 5.1 is here to stay (from my point of view at least) until
Mike Pall says otherwise.
Alexander.
Here is a strict array wrapper:
https://gist.github.com/759589
The newproxy magic is simple:
local obj = newproxy(true)
local MT = getmetatable(obj)
Since it returns us a bit of userdata with a metatable (the true
parameter) we can then override __len for the object.
For 5.2, __len can be overriden for regular tables so there is less
need for newproxy(). The only thing it can do is define __gc. I
briefly got excited about this for constructing module finalizers,
etc, but apparently there are doubts about the robustness of this
practice.
steve d.
> Here is a strict array wrapper:
Thank you!
> https://gist.github.com/759589
>
> The newproxy magic is simple:
>
> local obj = newproxy(true)
> local MT = getmetatable(obj)
>
> Since it returns us a bit of userdata with a metatable (the true
> parameter) we can then override __len for the object.
>
> For 5.2, __len can be overriden for regular tables so there is less
> need for newproxy(). The only thing it can do is define __gc. I
> briefly got excited about this for constructing module finalizers,
> etc, but apparently there are doubts about the robustness of this
> practice.
__gc is the only thing I use newproxy() for. It is very useful for
managing pools of objects (for example, network connections). If code
that uses the connection forgot to release it, __gc handler will do it
(eventually).
Alexander.
That struck me as the obvious use. Well, in Lua 5.2, it is fairly
trivial to implement newproxy as an extension ;)
BTW, the snippet shows another use of newproxy which I didn't
emphasize enough. And that is to make a really paranoid data type.
Since it is a udata proxy, a user cannot use the regular table
functions to break any invariants.
Naturally, one loses a little performance. But LuaJIT can be
surprisingly intelligent in optimizing these patterns.
steve d.