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!
One option is to use a light userdata, which allows you to allocate the object on the C++ heap. See the documentation for
lua_pushlightuserdata. Unfortunately a light userdata has no metatable. Even if you are willing to access it using Lua functions to do get/set you still have to do something like this:Unfortunately, because it’s a light userdata, there’s no real way to make this operation type-safe—all light userdata are treated the same, and they have no metatable.
The better solution is to allocate a full userdata on the Lua heap, with a proper metatable, whose contents are a single pointer to the object allocated on the C++ heap. Then you can follow the model in Programming in Lua. For examples you can look at the Lua
iolibrary to see howFILE *is handled. This way you can write your C interfaces using theluaL_checkudatafunction, and they will be safe, but you still will have the right to allocate your objects on the C++ heap instead of on the Lua heap.