lua-users home
lua-l archive

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



> -----Original Message-----
> From: lua-bounces@bazar2.conectiva.com.br [mailto:lua-
> bounces@bazar2.conectiva.com.br] On Behalf Of Jamie Webb
> Sent: Tuesday, July 06, 2004 11:17 AM
> To: Lua list
> Subject: Re: General questions.
> 
> On Tue, Jul 06, 2004 at 10:32:00AM -0700, William Roper wrote:
> > "If you know how to export your object's functionality to Lua then
you
> > know how to do it whether the object already exists or not.  The
only
> > difference is that, rather than allocating the object's memory via
> > lua_newuserdata, you will allocate space for a pointer to the object
> > and store the pointer in the userdata."
> >
> > I just reread this statement, could you elaborate on that a little?
> > All the examples I can find both in the book and on the wiki deal
with
> > creating new instances of a class in lua, not handling existing
> > instances of a class from C++.
> 
> // Create your class instance
> MyClass* instance = new MyClass();
> 
> // Create a Lua userdata to point to your object
> MyClass** ptr = (MyClass**) lua_newuserdata(L, sizeof(MyClass*));
> 
> // Make ptr point to your object
> *ptr = instance;
> 
> Now you have a userdata representing a pointer to your object sitting
> on the Lua stack. You'll need to set its metatable using the
> techniques described in the book and wiki, and then return that value
> to Lua.
> 
> Your methods will be created exatly is described in the book and wiki,
> except that you will need to extract the pointer from the userdata and
> dereference it in order to get your object, rather than the userdata
> itself being the object.

You could use the box and unbox pointer macros... (This pointer to
pointer stuff can be a read head spinner!)

#define lua_boxpointer(L,u) \
	(*(void **)(lua_newuserdata(L, sizeof(void *))) = (u))

#define lua_unboxpointer(L,i)	(*(void **)(lua_touserdata(L, i)))

Nick