我的做法略有不同,但大体上是相同的概念。我的不创建类,而只是移动它。我也在 C++ 端实现了它。
要实现我在 Lua 中所做的,您可以编写:
function moveClass(name)
oldGlobal = _G[name]
_G[name] = nil
return oldGlobal
end
要在 C++ 中实现它,你可以这样写:
luabind::module(lua) [
luabind::def("moveClass", +[](lua_State * lua, std::string name) {
// In the case the class does not exist, this will just
// remove nil and return nil. That essentially does nothing.
luabind::object oldGlobal = luabind::globals(lua)[name];
luabind::globals(lua)[name] = luabind::nil;
return oldGlobal;
})
];
所以现在如果你要使用它来移动你创建的类,你会这样做:
class 'MyClass'
myTable = {}
myTable.MyClass = moveClass 'MyClass'
作为额外说明,如果您希望 moveClass 函数在您尝试移动的类不存在的情况下给出错误,请使用 luabind::type(oldGlobal) == LUA_TNIL 来确定该类是否存在与否。
例子:
luabind::module(lua) [
luabind::def("moveClass", +[](lua_State * lua, std::string name) {
luabind::object oldGlobal = luabind::globals(lua)[name];
if (luabind::type(oldGlobal) == LUA_TNIL) {
throw std::runtime_error("Class does not exist.");
}
luabind::globals(lua)[name] = luabind::nil;
return oldGlobal;
})
];