C ++ classes & lua

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

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

However, I don't like this solution since my objects have constructors and destructors (and they are important since I use RAII and they care about reference counting).

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

Instead, I want to create an hte C ++ object myself and just have a way to make / set on them.

Does anyone have a good tutorial / link on this?

Tanks!

+2


a source to share


4 answers


One option is to use lightweight user data, which allows the object to be allocated on the C ++ heap. See the documentation for lua_pushlightuserdata

. Unfortunately, light user information has no metadata. Even if you want to access it using Lua get / set functions, you still need to do something like this:

static int myget(lua_State *L) {
   myclass thing = lua_touserdata(L, 1);
   lua_pushnumber(thing::getsize());
   return 1;
}

      



Unfortunately, since this is lightweight user data, there is no real way to make this operation type-safe: all lightweight user data is treated the same and has no meta tag.

The best solution is to allocate complete user data on the Lua heap with proper meta-tagging, whose content is the only pointer to the object allocated on the C ++ heap.You can then follow the model in Program in Lua. For example, you can look at the Lua library io

to see how it is processed FILE *

. This way you can write your C interfaces with a function luaL_checkudata

and they will be safe, but you will still have the right to allocate your objects on the C ++ heap, not the Lua heap.

+6


a source


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



+1


a source


I seem to remember a co-worker collecting things like Lua and C ++ objects as 1st class citizens and fully workable both ways.

If memory suits me, it was based on Lua ++ but I'm not sure at the moment, sorry.

+1


a source


Use a new placement. 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.)

0


a source







All Articles