【问题标题】:Lua/Luabind: Objects constructed by objects remain allocatedLua/Luabind:由对象构造的对象保持分配状态
【发布时间】: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 调用期间,只有FactoryChildDirect 对象被销毁。 ChildFactory1ChildFactory2 保持分配状态。在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 使用了一个在一段时间内运行的增量垃圾收集器,因此可能只有一次调用没有完成完整的收集+终结。

标签: c++ lua luabind


【解决方案1】:

adopt:用于跨语言转移所有权。

module(L)
[
    def("create", &create, adopt(result))
];

【讨论】:

    【解决方案2】:

    您应该从您的工厂返回一个智能指针(即boost::shared_ptr)。

    见:LuaBind Documentation # smart pointer

    LuaBridge docu中的讨论

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-06
      • 1970-01-01
      • 2018-10-07
      • 2012-08-14
      • 1970-01-01
      • 2021-06-21
      • 2017-05-14
      相关资源
      最近更新 更多