参考tolua++ 的reference,但是那个manu没有完整的demo,所以补一个。(总感觉自己亲自实现一下,心里才有底)
1 #include <stdio.h> 2 #include <string> 3 #include <iostream> 4 5 using namespace std; 6 7 class Animal{ 8 public: 9 Animal(std::string name); 10 void setAge(int age); 11 int getAge(); 12 void sound(); 13 private: 14 string name; 15 int age; 16 }; ~
Animal.cpp
1 #include "Animal.h" 2 3 Animal::Animal(std::string name) 4 :age(0) 5 { 6 this->name = name; 7 } 8 void Animal::setAge(int age) 9 { 10 this->age = age; 11 } 12 13 int Animal::getAge() 14 { 15 return this->age; 16 } 17 18 void Animal::sound() 19 { 20 cout << " -- Animal name: " << this->name << " and it's Age:"<< this->age << endl; 21 }
对应的pkg为:
toluaTest.pkg
1 $#include "Animal.h" 2 3 4 class Animal{ 5 public: 6 Animal(std::string name); 7 void setAge(int age); 8 int getAge(); 9 void sound(); 10 }; 11
主文件,main.cpp 这个文件纯粹就是调用lua去执行test.lua;
1 #include <stdio.h> 2 #include <string> 3 #include <iostream> 4 5 extern "C"{ 6 #include "lua.h" 7 #include "lauxlib.h" 8 #include "lualib.h" 9 } 10 11 #include "main.h" 12 13 using namespace std; 14 15 16 int main() 17 { 18 lua_State *L = luaL_newstate(); 19 luaL_openlibs(L); 20 21 tolua_toluaTest_open (L); 22 // 23 if (luaL_loadfile(L, "test.lua") || lua_pcall(L, 0, 0, 0)){ 24 cout << "cannot run config. file:" << lua_tostring(L,-1) << endl; 25 } 26 27 lua_close(L); 28 return 0; 29 }
1 #ifndef __TOLUATEST_MAIN_H_ 2 #define __TOLUATEST_MAIN_H_ 3 4 #ifdef __cplusplus 5 extern "C" { 6 #endif 7 #include "tolua++.h" 8 #ifdef __cplusplus 9 } 10 #endif 11 12 TOLUA_API int tolua_toluaTest_open (lua_State* tolua_S); 13 14 #endif
最后Makefile
1 all: toluaTest.cpp 2 g++ -g3 -o test Animal.cpp toluaTest.cpp main.cpp -ltolua++ -llua 3 4 toluaTest.cpp: 5 tolua++ -o toluaTest.cpp toluaTest.pkg 6 7 clean: 8 rm toluaTest.cpp 9 rm -R *dSYM *out test
bash-3.2$ m tolua++ -o toluaTest.cpp toluaTest.pkg g++ -g3 -o test Animal.cpp toluaTest.cpp main.cpp -ltolua++ -llua bash-3.2$ ./test test lua access C++ Class -- Animal name: dog and it's Age:100 dog age is :100 bash-3.2$
抱歉,格式没有排好,凑合着看吧:)