Question

I have a simple Lua script

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

that uses two C++ exposed objects (trough 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)
    ];
}

I call the function

luabind::object obj = luabind::call_function< luabind::object >(LuaState, "TestFunction", IdParam);

if ( obj.is_valid() )
{
        ....
}

lua_gc(LuaState, LUA_GCCOLLECT, 0);

During lua_gc call only Factory and ChildDirect objects are destroyed. ChildFactory1 and ChildFactory2 remains allocated. The lua stack remains balanced (has same value - 5 - some tables ) after the luabind::call_function.

What is the problem ? The objects created by Factory remain somehow referenced ? By who ?

CreateChild body is

TestChild* TestParent::CreateChild(std::string strname)
{
    return new TestChild(strname);
}

The ownership of the new constructed object should be taken by lua object and destroyed if ChildFactory1 or ChildFactory2 is nil-ed or out of scope.

Was it helpful?

Solution

adopt: Used to transfer ownership across language boundaries.

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

OTHER TIPS

You should return a smart pointer (i.e. a boost::shared_ptr) from your factory.

see: LuaBind Documentation # smart pointer

and a discussion in the LuaBridge docu

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top