|
#include <iostream> |
|
#include <memory> |
|
|
|
#include <lua.h> |
|
#include <lualib.h> |
|
#include <lauxlib.h> |
|
|
|
#include <LuaBridge/LuaBridge.h> |
|
|
|
|
|
namespace luabridge { |
|
// register shared_ptr as container |
|
template <class T> |
|
struct ContainerTraits <std::shared_ptr<T> > |
|
{ |
|
typedef T Type; |
|
|
|
static T* get (std::shared_ptr<T> const& c) |
|
{ |
|
return c.get(); |
|
} |
|
}; |
|
// make sure shared_ptr isn't usable with not instrumented types |
|
template <class T> |
|
struct ContainerTraits2< std::shared_ptr<T> > { }; |
|
} |
|
|
|
// class with shared_from_this that friends ContainerTraits2 |
|
class A : public std::enable_shared_from_this<A> { |
|
public: |
|
friend class luabridge::ContainerTraits2< std::shared_ptr<A> >; |
|
|
|
A(int v) : value(v) { std::cout << "A::A(" << value << ")" << std::endl; } |
|
~A() { std::cout << "A::~A(" << value << ")" << std::endl; } |
|
|
|
int value; |
|
|
|
static void register_lua(lua_State *L) |
|
{ |
|
using namespace luabridge; |
|
getGlobalNamespace (L) |
|
.beginNamespace ("test") |
|
.beginClass <A> ("A") |
|
.addConstructor<void(*)(int), std::shared_ptr<A> >() |
|
.endClass () |
|
.endNamespace (); |
|
} |
|
|
|
}; |
|
|
|
namespace luabridge { |
|
// second traits are able to obtain a shared_ptr from a raw pointer |
|
template <> |
|
struct ContainerTraits2< std::shared_ptr<A> > |
|
{ |
|
static std::shared_ptr<A> getContainer(A *t) |
|
{ |
|
return t->shared_from_this(); |
|
} |
|
}; |
|
} |
|
|
|
int main(int argc, char *argv[]) { |
|
int iarg; |
|
lua_State *L = luaL_newstate(); |
|
|
|
luaL_openlibs(L); |
|
A::register_lua(L); |
|
{ |
|
std::shared_ptr<A> a(new A(1)); |
|
|
|
luabridge::setGlobal (L, a, "a"); |
|
|
|
lua_getglobal(L, "a"); |
|
std::shared_ptr<A> a2 = luabridge::Stack< std::shared_ptr<A> >::get(L,1); |
|
|
|
int s = luaL_dostring(L, "b = test.A(2)"); |
|
if(s != 0) { |
|
std::cerr << "Error: " << lua_tostring(L, -1) << std::endl; |
|
lua_pop(L, 1); |
|
} |
|
|
|
lua_getglobal(L, "b"); |
|
std::shared_ptr<A> b = luabridge::Stack< std::shared_ptr<A> >::get(L,1); |
|
|
|
s = luaL_dostring(L, "c = a"); |
|
if(s != 0) { |
|
std::cerr << "Error: " << lua_tostring(L, -1) << std::endl; |
|
lua_pop(L, 1); |
|
} |
|
|
|
lua_getglobal(L, "c"); |
|
std::shared_ptr<A> c = luabridge::Stack< std::shared_ptr<A> >::get(L,1); |
|
|
|
} |
|
|
|
lua_close(L); |
|
|
|
return 0; |
|
} |
You can replace
with