【发布时间】:2014-01-16 14:37:40
【问题描述】:
我有一个简单的Lua 脚本
function TestFunction(Id)
local Factory = TestParent();
local ChildDirect = TestChild("DirectCall");
local ChildFactory1 = Factory:CreateChild("Factory1");
local ChildFactory2 = Factory:CreateChild("Factory2");
result = Ret()
return result
end
使用两个 C++ 暴露对象(通过luabind)
void TestParent::RegisterToLua(lua_State* lua)
{
// Export our class with LuaBind
luabind::module(lua)
[
luabind::class_<TestParent>("TestParent")
.def(luabind::constructor<>())
.def("CreateChild", &TestParent::CreateChild)
];
}
void TestChild::RegisterToLua(lua_State* lua)
{
// Export our class with LuaBind
luabind::module(lua)
[
luabind::class_<TestChild>("TestChild")
.def(luabind::constructor<std::string>())
.def("GetValue", &TestChild::GetValue)
];
}
我调用函数
luabind::object obj = luabind::call_function< luabind::object >(LuaState, "TestFunction", IdParam);
if ( obj.is_valid() )
{
....
}
lua_gc(LuaState, LUA_GCCOLLECT, 0);
在lua_gc 调用期间,只有Factory 和ChildDirect 对象被销毁。 ChildFactory1 和 ChildFactory2 保持分配状态。在luabind::call_function 之后,lua 堆栈保持平衡(具有相同的值 - 5 - 一些表)。
有什么问题? Factory 创建的对象仍然以某种方式被引用?由谁?
CreateChild 主体是
TestChild* TestParent::CreateChild(std::string strname)
{
return new TestChild(strname);
}
如果 ChildFactory1 或 ChildFactory2 为 nil-ed 或超出范围,则新构造对象的所有权应由 lua 对象获取并销毁。
【问题讨论】:
-
只是一个预感,但尝试连续调用 lua_gc 两次。 Lua 使用了一个在一段时间内运行的增量垃圾收集器,因此可能只有一次调用没有完成完整的收集+终结。