在C++中使用Lua

来源:互联网 发布:mac如何处理.ds store 编辑:程序博客网 时间:2024/05/06 10:51

 1. 下载Lua源码
Lua源码下载地址 http://www.lua.org/download.html

 

2. 创建Lua静态库
在vs2008中创建一个静态库项目(我创建的叫LuaLib),注意:一定要取消“预编译头”选项;
建成后将Lua源码的.h和.c加入该项目
进入项目属性,修改编译输出,方便其他项目使用lib库
配置属性->常规->输出目录,设置为“$(SolutionDir)\lib\”
配置属性->管理员->常规->输出文件,设置为“$(OutDir)\$(ProjectName)d.lib”
编译,有一些警告,可以不用管
在Lualib文件夹下的lib文件中有输出的lualibd.lib

 

3. 创建Test
在LuaLib解决方案中新建Win32控制台程序testLua

 

4. 引入前面生产的Lualib库
进入testLua项目属性
配置属性->C/C++->常规->附加包含目录,设置为“..\lib\”
配置属性->链接器->常规->附加库目录,设置为“..\lib\”
配置属性->链接器->输入->附加依赖项,设置为“Lualibd.lib”
同时还需要将Lua源码中的以下几个头文件放在lib文件夹中,方便项目引用
lauxlib.h
lua.h
luaconf.h
lualib.h

 

5. 编写C++代码

#include "stdafx.h"#include <iostream>#include <string>using namespace std;extern "C"{#include "lua.h"#include "lualib.h"#include "lauxlib.h"}int fcAdd(lua_State *lu){int a = lua_tointeger(lu, 1);int b = lua_tointeger(lu, 2);lua_pushnumber(lu, a+b);//结果压栈return 1;//返回1个结果}int _tmain(int argc, _TCHAR* argv[]){int nret = 0;lua_State *lu = luaL_newstate();luaL_openlibs(lu);//栈操作lua_pushinteger(lu, 2);lua_pushinteger(lu, 3);int n = lua_tointeger(lu, 1);n = lua_tointeger(lu, 2);int nStack = lua_gettop(lu);lua_pop(lu, 2);nStack = lua_gettop(lu);//执行内存脚本string str = "print (\"Hello world!\")";luaL_loadbuffer(lu, str.c_str(), str.length(), "line");lua_pcall(lu, 0,0,0);//加载脚本中定义的变量nret = luaL_dofile(lu, "..\\scripts\\test.lua");lua_getglobal(lu, "aa");lua_getglobal(lu, "bb");int bb = lua_tointeger(lu, -1);int aa = lua_tointeger(lu, -2);//执行脚本中定义的无参函数lua_getglobal(lu, "hello");nret = lua_pcall(lu, 0,0,0);//执行脚本中定义的有参函数lua_getglobal(lu, "fadd");lua_pushnumber(lu, aa);lua_pushnumber(lu, bb);nret = lua_pcall(lu, 2,1,0);if (nret != 0){const char *pc = lua_tostring(lu, -1);cout << pc;}else{nret = lua_tointeger(lu, -1);cout << "调用脚本函数:" << endl;cout << aa << " + " << bb << " = " << nret << endl;lua_pop(lu, 1);}//脚本中调用C++函数lua_pushcfunction(lu, fcAdd);lua_setglobal(lu, "fcAdd");lua_getglobal(lu, "fc");lua_pushnumber(lu, aa);lua_pushnumber(lu, bb);nret = lua_pcall(lu, 2,1,0);if (nret != 0){const char *pc = lua_tostring(lu, -1);cout << pc;}else{nret = lua_tointeger(lu, -1);cout << "调用C++函数:" << endl;cout << aa << " + " << bb << " = " << nret << endl;lua_pop(lu, 1);}lua_close(lu);std::system("pause");return 0;}

 

6.  Lua脚本代码

在LuaLib文件夹下创建scripts文件夹,在其中创建test.lua,代码如下:

aa=2;bb=3;function hello(a,b) print ("Hello in script!")endfunction fadd(a,b) return a+bendfunction fc(a,b)  return fcAdd(a,b)end



示例源码下载地址:http://download.csdn.net/detail/shellching/4015889
 

原创粉丝点击