LuaBridge 中C++类和继承示例

luabridge不是一个陌生的名字,GIT上已经有3-4年多没有更新。将lua和C++相互调用封装的很方便,比如以下示例代码:

//////////////////////////////////////////////////////////////////////////
// test code for luabridge

class A 
{
public:
  A()
  {

  }

  ~A()
  {

  }

public:
  std::string get_title() const
  {
    return title;
  }

  void set_title( const std::string& s )
  {
    title = s;
  }

private:
  std::string title;
};

class B : public A 
{
public:
  B() : A()
  {

  }

  ~B()
  {

  }
};


void trace( const std::string& strOutput)
{
  OutputDebugStringA(strOutput.c_str());
  OutputDebugStringA("
");
}

class lua_test
{
public:
  lua_test() 
    : L_(0)
    , B_()
  {
    L_ = luaL_newstate();  
    luaL_openlibs(L_);
    luaopen_string(L_);

    luabridge::getGlobalNamespace( L_ )
      .addFunction( "trace", trace )
      .beginNamespace( "test" )
        .beginClass< A >( "A" )
          .addConstructor <void (*) (void)> ()
          .addProperty( "title", &A::get_title, &A::set_title )
        .endClass()

        .deriveClass< B, A >( "B" )
          .addConstructor <void (*) (void)> ()
        .endClass()
      .endNamespace()
    ;
  }

  ~lua_test()
  {
    lua_close( L_ );
  }

  bool run( ) 
  {
    luabridge::setglobal<A*>( L_, (A*)&this->B_, "classb" );
    B_.set_title( "B.title ");

    std::string lua_string;
    FILE* f = fopen( "D:/test.lua", "r" );
    if( f ) {
      char buf[2048] = {0};
      int r = fread( buf, 1, sizeof( buf ), f );
      if( r > 0 ) 
        lua_string = std::string( buf, r );
      fclose( f );
      f = 0;
    }
    
    try
    {
      //2.加载Lua文件  
      int bRet = luaL_loadstring( L_, lua_string.c_str() );  
      if(bRet) {  
        OutputDebugStringA(lua_tostring( L_, -1 ) );
        return false;
      }

      //3.运行Lua文件   CHttpCall::~CHttpCall
      bRet = lua_pcall( L_, 0, 0, 0);  
      if(bRet)  
      {
        OutputDebugStringA(lua_tostring( L_, -1 ) );
        return false;
      }
    } catch (...) {
      OutputDebugStringA( lua_tostring( L_, -1 ) );
    }
    return true;
  }


private:
  lua_State* L_;
  B B_;
};

// 运行代码

  lua_test t;
  t.run();

lua_test 打开D:/test.lua文件并执行test_func方法,该方法创建了一个B的实例并打印实例的title属性以及全局对象classb的title属性

test.lua:

function test_func()
  local a = test.B();
  a.title = "abcdefg";
  trace( a.title )
  trace( classb.title );
end

test_func();

在此记录一下。

原文地址:https://www.cnblogs.com/lovelylife/p/5436056.html