tolua++ 是用来把 C++代码 生成 在Lua中使用的接口的工具,编译步骤比较繁琐。
1、下载lua5.1.4,解压后,新建空项目,修改成静态库lib ,在C++ 代码生成选项卡 中设置 运行库 为 多线程 DLL (/MD) ,然后把安全检查 设置为 禁用安全检查 (/GS-)
把lua5.1.4 src目录下的 除了 lua.c luac.c 的所有文件添加到项目中,编译。
编译成功后获得 lua5.1.4.lib 。
2、下载 tolua++ ,解压后,新建空项目,其它设置和上面一样,添加 tolua++ 文件夹中的 src/lib/ 里面的所有代码到项目中,编译成静态库。
编译成功后获得 tolua++.lib
到 tolua++ 文件夹中的 win32/vc7 中,打开 toluaapp.sln ,设置好 lua 头文件目录,把lua5.1.4.lib 添加到链接库 ,添加 tolua++ 目录的include 目录到头文件目录,把 tolua++.lib 添加到链接库,编译。
编译成功后,在tolua++目录的bin 中获得 tolua++.exe
3、编写Student 类来作为测试
Student.h
- #pragma once
-
- #include<iostream>
- using namespace std;
-
- class Student
- {
- public:
- Student();
- ~Student();
-
- void Run();
-
- void Run(int a);
- };
Student.cpp
- #include "Student.h"
-
-
- Student::Student()
- {
- }
-
- void Student::Run()
- {
- cout << "Student Run" << endl;
- }
-
- void Student::Run(int a)
- {
- cout << "Student Run" <<a<< endl;
- }
-
- Student::~Student()
- {
- }
为Student 类创建 pkg文件
Student.pkg
- $#include"Student.h"
-
- class Student
- {
- public:
- Student();
- ~Student();
-
- void Run();
- void Run @ Run2(int a);
- };
把tolua++.exe 到 Student 的类文件目录,右键命令行
- "tolua++.exe" -o lua_Student.cpp Student.pkg
生成成功获得 lua_Student.cpp
4、创建测试项目在lua 脚本中使用 Student 类
创建空项目,项目中设置好 lua5.1.4 和 tolua++ 的头文件目录 ,以及引用 lua5.1.4.lib 和 tolua++.lib 。
然后把 Student 类 和生成的 lua_Student.cpp 添加到项目中。
main.cpp
- #include <stdio.h>
- #include<windows.h>
-
- extern "C"
- {
- #include "lua.h"
- #include "lualib.h"
- #include "lauxlib.h"
- #include "luaconf.h"
- }
- #include "tolua++.h"
- #include"Student.h"
-
- extern int tolua_Student_open(lua_State* tolua_S);
-
- int main(int argc, char* argv[])
- {
- lua_State* L = luaL_newstate();
- luaL_openlibs(L);
-
- tolua_Student_open(L);
-
- luaL_dofile(L, "./test.lua");
- lua_close(L);
-
- system("pause");
- return 0;
- }
lua脚本文件 test.lua
- studentB=Student:new() --实例化Student全局对象
-
- function Run()
- studentB:Run();
- end
-
- function Run2(a)
- studentB:Run2(a);
- end
-
- function show()
- local b = {}
- local index
-
- for index = 1,10,1 do
- print(index)
- end
- end
-
- show()
-
- Run()
-
- Run2(10)
项目打包下载 (lua5.1.4 + luajit + toluapp)
百度网盘:
- http://pan.baidu.com/s/1i3xvykt
CSDN下载:
- http://download.csdn.net/detail/cp790621656/9235459