自从学习了lua这个脚本语言以后,无时不想着将他与c/c++联系起来,看看他真正的威力。奈何水平有限,网上找的代码不管怎样都没法运行成功。我知道是我少了某一步可是又不知道到底少了什么,因而就在各大博客、网站、论坛不断的摸索测试。我也不知道花了多长时间。总之在今天测试成功了。我把我测试遇到的问题和解决过程贴出来供你们参考。ios
1、lua环境的搭建 c++
建议去网上下载luaforwindow,这是一款跟众多window系统的软件同样,安装起来简单方便,一路点next就能搞定了。并且他还包含了有用的与lua有关的基本工具编辑器
他包括如下组件:函数
Lua(Command Line):lua的一个命令行编辑器。简单轻便,习惯命令行编(zhuang)辑(bi)的能够试试。工具
Lua Examples: 包含lua使用的一些例子。学习
LuaForWindows Documentation :LuaForWindows这款软件的一些说明测试
QuickLuaTour : lua快速入门向导,没什么用,看看就好网站
SciTE:lua的一个不错的文本编辑器。能够在里面测试一些lua代码,能够运行测试。前提是要先保存文件在运行,不然他没有任何反应。别问我是怎么知道的,心塞塞ui
Documentation:里面包含lua的帮助文档,最有用的就是他了吧。lua
安装好后Lua的环境就算是搭建好了。咱们用命令行简单来测试一下:
Ok,木有问题
2、VS环境配置
这一步是最重要的,一开始我是去lua官网下载的源文件再把他们添加到vs项目,虽然编译是没有问题了,可是在测试运行的时候连接仍是出现了问题。很明显我是少了什么东东。后来我改用下面的方法解决了问题。
定位到Lua的安装文件夹,个人是:
肯定后返回
至此环境基本就配置好了。相似下面:
如今咱们用代码测试一遍:
#include "stdafx.h" #include <iostream> #include <string.h> using namespace std; extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } void main() { //1.建立一个state lua_State *L = luaL_newstate(); //2.入栈操做 lua_pushstring(L, "Hello World~"); //3.取值操做 if (lua_isstring(L, 1)) { //判断是否能够转为string cout << lua_tostring(L, 1) << endl; //转为string并返回 } //4.关闭state lua_close(L); system("pause"); return; }
是否是木有问题啦╮(╯▽╰)╭
上面咱们已经把须要的环境什么的都配置好了,如今重头戏上场( ̄︶ ̄)
function Communicate(name) return ("Hello "..name..", I`m in Lua"); end
#include "stdafx.h" #include <iostream> #include <string.h> using namespace std; extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } void main() { string hello = "This is Zack, I`m in C++"; cout << hello.c_str() << endl; //建立Lua状态 lua_State *L = luaL_newstate(); if (L == NULL) { return; } //加载Lua文件 int bRet = luaL_loadfile(L, "test.lua"); if (bRet) { cout << "load file error" << endl; return; } //运行Lua文件 bRet = lua_pcall(L, 0, 0, 0); if (bRet) { cout << "pcall error" << endl; return; } //读取函数 lua_getglobal(L, "Communicate"); // 获取函数,压入栈中 lua_pushstring(L, "Zack"); // 压入参数 int iRet = lua_pcall(L, 1, 1, 0);// 调用函数,调用完成之后,会将返回值压入栈中,第一个1表示参数个数,第二个1表示返回结果个数。 if (iRet) // 调用出错 { const char *pErrorMsg = lua_tostring(L, -1); cout << pErrorMsg << endl; lua_close(L); return; } if (lua_isstring(L, -1)) //取值输出 { string Result = lua_tostring(L, -1); cout << Result.c_str() << endl; } //关闭state lua_close(L); system("pause"); return; }
结果:
嗯,大功告成。就酱紫了╰( ̄▽ ̄)╮╭(′▽`)╯╰( ̄▽ ̄)╮