c++lualuabind

Lua/Luabind: Objects constructed by objects remain allocated


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.


Solution

  • adopt: Used to transfer ownership across language boundaries.

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