Disclaimer: I wrote a library that I want to recommend
You might want to try this LuaWrapper library, which sounds like it will handle what you are trying to do. It is not even a library, it is just one header file.
You can use luaW_push<MyType>(L, myObj); to push your objects to Lua. Lua will not be the owner of the objects you created from C ++ unless you run luaW_hold<MyType> . In other words, if you do not tell Lua, this will not cause your object to crash.
Conversely, you can use MyType.new() in your Lua code to create an object that Lua owns. This will be garbage collection, as you would expect. If you want to transfer ownership of C ++, you can call luaW_release<MyType> on your object.
There are also functions such as luaW_to<MyType> and luaW_check<MyType> , and to a limited extent it correctly supports inheritance from basic types (although at the moment it allows only one inheritance). I find that it greatly simplifies my own attempts to use C ++ and Lua together, because it makes managing the ownership pointer very easy.
source share