Lua与C++的交互测试
上面我们已经把需要的环境什么的都配置好了,现在重头戏上场( ̄︶ ̄)
1.我们建一个test.lua文件;
function Communicate(name)
return ("Hello "..name..", I`m in Lua");
end
1.我们调用lua文件的cpp代码
#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);// 调用函数,调用完成以后,会将返回值压入栈中,2表示参数个数,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;
}
结果:

嗯,大功告成。
本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-01/126948.htm
