Search code examples
c++lualua-apitolua++

tolua++: Transfer pointer ownership to lua gc


Is there a way to return objects allocated on the the heap to lua without 'caching' references to them?

Consider the following:

class foo
{
    char const* bar() const
    {
        char* s = malloc(...);
        ...
        return s; // << Leak. How to transfer the ownership of 's' to lua?
    }
};

If I return a string to allocated memory i have to delete it. Is there a way to transfer the ownership to lua?

Or is it even possible to get the lua_state* to implement string returning by myself using lua_pushstring(...)?


Solution

  • By declaring a parameter 'lua_Sate* state' tolua++ will pass the Lua-State to the function.

    With a return type of type 'lua_Object' you can return the stack-index to a lua object.

    PKG

    lua_Object MyFunctionReturningATable(lua_State* s);
    

    CPP

    lua_Object MyFunctionReturningATable(lua_State* s)
    {
        lua_newtable(s);
    
        ...
    
        return lua_gettop();
    }