Delegating C++ object memory allocation to Lua
So far, we have been creating C++ objects in C++ and making Lua store its pointer in userdata. This was done in LuaModuleExporter::luaNew
, as follows:
static int luaNew(lua_State *L) { ... T **userdata = reinterpret_cast<T **>( lua_newuserdatauv(L, sizeof(T *), 0)); T *obj = luaModuleDef.createInstance(L, nullptr); *userdata = obj; ... }
In this case, the Lua userdata only stores a pointer. As you may recall, Lua userdata can represent a much larger piece of memory, so you might be wondering if we can store the whole C++ object in userdata, instead of just the pointer. Yes, we can. Let’s learn how to do it.
Using C++ placement new
In C++, the most common way to create an object is to call new T()
. This does two things:
- It creates a piece...