见我上篇,手动bind lua和C++;
《lua 操作 C++的类 ;manipulate c++ class with lua》
http://blog.youkuaiyun.com/chenee543216/article/details/12074771
本篇deom一下如何用tolua++ 这个工具(compileer+lib)来更加简单的实现我们需要的功能。
首先我们需要导出给lua的类如下:
Animal.h
对应头文件:main.h( 这个其实就是为了extern tolua_toluaTest_open(L);
编译,执行结果:
《lua 操作 C++的类 ;manipulate c++ class with lua》
http://blog.youkuaiyun.com/chenee543216/article/details/12074771
本篇deom一下如何用tolua++ 这个工具(compileer+lib)来更加简单的实现我们需要的功能。
参考tolua++ 的reference,但是那个manu没有完整的demo,所以补一个。(总感觉自己亲自实现一下,心里才有底)
首先我们需要导出给lua的类如下:
Animal.h
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 }
对应头文件:main.h( 这个其实就是为了extern tolua_toluaTest_open(L);
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$
抱歉,格式没有排好,凑合着看吧:)