Search code examples
c++bindinglualuabridge

Luabridge: Returning C++ lifetime managed object


This snipped works for basic types:

int CreateBasicObject(lua_State *L)
{
    int ret0;

    lua_pushinteger(L, ret0);

    return 1;
}

and in lua it looks like this:

local NewObject=CreateBasicObject()

How would I go about returning classes instead of ints?

push(L,&MyObject);
return 1;

does not seem to work correctly, lua portion looks like this:

self.MyObject=Screen.MyObject(); 

And the error is:

attempt to index field 'MyObject' (a number value)

Solution

  • In the newest LuaBridge version you can use RefCountedPtr for example:

    some C++ definition

    struct A {};
    
    static RefCountedPtr<A> SomeA() {
     return RefCountedPtr<A>(new A);
    }
    

    and the binding:

    luabridge::getGlobalNamespace(L)
      .beginClass<A>("A")
       .addConstructor< void (*) (), RefCountedPtr<A> >()
      .endClass()
    
      .addFunction("SomeA",&SomeA);
    

    now you can return A objects safely and pass them to other Lua-bound functions as RefCountedPtr<A>

    in lua you can then use it like that:

    local a=A()
    --do something with a...
    
    local b=SomeA()
    --do something with b...