使用lua5.3.3 +vs 2013
直接包含lua源码编译
c++ lua_pcall 脚本中的 lop_int 报错,
错误消息是"Hello.lua:12: attempt to call a nil value (global 'print')" const char *
感觉很奇怪,print 明明是一个function啊 为啥会变为const char*
万分感激!
======
lua 脚本 “Hello.lua”
str = "I am so cool"
tb1 = {name = "大p", id = 20114442}
list = nil
function add(a,b)
return a + b
end
function lop_int()
local i
for i=1,10 do
print(i)
end
end
=====
c++代码
#include "stdafx.h"
#include "D:\lua5\src\lua.hpp"
#include "iostream"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "hello,lua" << endl;
lua_State *L = luaL_newstate();
if (L == NULL)
{
return 0;
}
int bRet = luaL_loadfile(L, "Hello.lua");
if (bRet)
{
cout << "load lua script error\n" << endl;
return 0;
}
//运行lua文件
bRet = lua_pcall(L, 0, 0, 0);
if (bRet)
{
cout << "pcall error\n" << endl;
return 0;
}
//读取变量
lua_getglobal(L, "str");// LUA_ERRSYNTAX
string str = lua_tostring(L, -1);
cout << "str = " << str.c_str() << endl;
//读取table
lua_getglobal(L, "tb1");
lua_getfield(L, -1, "name");
str = lua_tostring(L, -1);
cout << "tb1:name = " << str.c_str() << endl;
//读取函数
lua_getglobal(L, "add");
lua_pushnumber(L, 11);//第一个参数
lua_pushnumber(L, 8);
int iRet = lua_pcall(L, 2, 1, 0);
if (iRet)
{
const char *pErrMsg = lua_tostring(L, -1);
cout << "ErrMsg : " << pErrMsg << endl;
lua_close(L);
return 0;
}
if (lua_isnumber(L, -1))
{
double fValue = lua_tonumber(L, -1);
int iValue = lua_tonumber(L, -1);
cout << "Result is " << fValue << " - " << iValue << endl;
}
lua_getglobal(L,"lop_int");
iRet = lua_pcall(L, 0, 0, 0);
if (iRet)
{
const char *pErrMsg = lua_tostring(L, -1);
cout << "ErrMsg : " << pErrMsg << endl;
lua_close(L);
return 0;
}
lua_close(L);
return 0;
}
[注意]传递专业知识、拓宽行业人脉——看雪讲师团队等你加入!