tags:

views:

262

answers:

4
+2  Q: 

c++ classes & lua

I want to have C++ objects that I can read/write in both C++ & Lua.

I have looked at: http://www.lua.org/pil/28.html

However, I do not like that solution, since my objects have constructors & destructors (and they are important as I use RAII and these take care of reference counts).

What I don't like in the PIL solution is that the object is allocated in Lua's heap.

What i want instead, is to create hte C++ object on my own, and just have lua have a way to do get/set on them.

Does anyone have a good tutorial/link on this?

Tanks!

+1  A: 

Seems like a factory is the way to go? E.g. instead of just dynamically creating your object in Lua via "standard" means, can you call a function for Create and Destroy?

dash-tom-bang
err, Lua does the memory allocation; you're sugesting in place constructors?
anon
I'm saying that you call a function that you implement in C or C++ to new and delete your object, which you then hand to Lua to let it wrap or whatever it does. This seems less prone to issues than trying to hook into the Lua memory allocation scheme, but I have to admit I've never done anything like this. In short- all Lua knows about is the pointer. Your factory functions (Thing* CreateThing() and void DestroyThing(Thing*)) take care of the actual C++ magic.
dash-tom-bang
+5  A: 
Norman Ramsey
A: 

Use the placement new. See here for a handy template:

template< typename T >
void my_newuserdata( lua_State * L ) {
   new ( reinterpret_cast< T * >( lua_newuserdata( L, sizeof( T ) ) ) ) T();
}

template< typename T >
int my_gc( lua_State * l ) {
   reinterpret_cast< T * >( lua_touserdata( L, 1 ) )->~T();
   return 0;
}

(Untested, see link above for details.)

Alexander Gladysh
+1  A: 

I seem to remember a co-worker getting that kind of thing going, both Lua and C++ objects as 1st-class citizens and completely operable in both directions.

If memory serves me right it was based upon Lua++ but at this point I am not sure, sorry.

ted_j