Luabridge: Returning C++ lifetime managed object

徘徊边缘 提交于 2019-12-11 11:46:11

问题


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)

回答1:


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...


来源:https://stackoverflow.com/questions/16206952/luabridge-returning-c-lifetime-managed-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!