3

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(...)?

greatwolf
  • 20,287
  • 13
  • 71
  • 105

2 Answers2

2

You can pass your string into Lua with the lua_pushstring function and free it afterwards:

Pushes the zero-terminated string pointed to by s onto the stack. Lua makes (or reuses) an internal copy of the given string, so the memory at s can be freed or reused immediately after the function returns. The string cannot contain embedded zeros; it is assumed to end at the first zero.

If you really want ownership to be transfered, consider wrapping your string into appropriate object with its own metatable and implementing __gc function.

DennisS
  • 253
  • 1
  • 15
  • The problem with `push_string` is that i dont have access to the `lua_state` in my c++ functions (?) –  Jan 14 '16 at 17:41
0

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();
}