Lua-l: Support for lua_next on C userdata objects

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Lua-l: Support for lua_next on C userdata objects

drake-3
Hello,

So I'm trying to implement a bridge between Lua and a C++ system.  The  
system (kroll) basically supports multiple language bindings and  
allows calls between them.  Thus my Lua module allows we to call  
Javascript functions from Lua and Lua object from Javascript.

Now the way I'm currently doing this (the only way I can see) is to  
have a Lua "proxy object", implemented in C.  This is basically a  
userdata object with a metatable which has entries for __index,  
__newindex and __gc.  Basically the __index call converts basic types  
from kroll into Lua, complex types create a new instance of my proxy  
class ... all works well and I can pass object all over the place.

Now the problem.  Currently the only thing I don't support is Lua code  
iterating (pairs, next) over my proxy object.  As such I'm unable  
(from Lua) to do something like:

for key, val in pairs( proxyobject ) do
        print( "key: "..key )
end

Now, whilst its not ideal, I can live with that as I can work around  
the need for Lua to enumerate items from kroll.  Unfortunately there  
are some cases where my Lua code (on the Kroll -> Lua side) trys to  
enumerate not an actual Lua table but a one of my userdata objects  
(from the Lua -> Kroll side).  What all this means is that lua_next is  
called to try to get the available indexs on my userdata proxyobject.

How do I implement something with the lua C api to handle calls on it  
by lua_next?

One other point.  As I'm passing references to Lua objects off into  
the world of C++ (kroll), how do I (in C) increment/decrement the Lua  
reference count so that the Lua gc doesn't try to discard it and cause  
my code to go pop?

Thanks in advance

Rich

Reply | Threaded
Open this post in threaded view
|

Re: Lua-l: Support for lua_next on C userdata objects

Javier Guerra Giraldez
On Wed, May 20, 2009 at 4:28 PM, drake <[hidden email]> wrote:
> How do I implement something with the lua C api to handle calls on it by
> lua_next?

the easiest way is to replace the next() function with your own, that
honours some '__next' field on your metatable, and call the original
next() if there's none.

something like this (untested):

local oldnext=next
function next(t)
    local mt = getmetatable(t)
    nx = mt and mt.__next or oldnext
    return nx(t)
end

> One other point.  As I'm passing references to Lua objects off into the
> world of C++ (kroll), how do I (in C) increment/decrement the Lua reference
> count so that the Lua gc doesn't try to discard it and cause my code to go
> pop?

store them in the registry


--
Javier