LuaBridge 中C++类和继承示例
生活随笔
收集整理的這篇文章主要介紹了
LuaBridge 中C++类和继承示例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
luabridge不是一個陌生的名字,GIT上已經(jīng)有3-4年多沒有更新。將lua和C++相互調(diào)用封裝的很方便,比如以下示例代碼:
// // test code for luabridgeclass 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("\n"); }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::~CHttpCallbRet = 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文件并執(zhí)行test_func方法,該方法創(chuàng)建了一個B的實例并打印實例的title屬性以及全局對象classb的title屬性
test.lua:
function test_func()local a = test.B();a.title = "abcdefg";trace( a.title )trace( classb.title ); endtest_func();在此記錄一下。
?
轉(zhuǎn)載于:https://www.cnblogs.com/lovelylife/p/5436056.html
總結(jié)
以上是生活随笔為你收集整理的LuaBridge 中C++类和继承示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: struts 的 MVC ,自己堆栈跟踪
- 下一篇: SpringMVC+hibernate+