刚开始学习C++调用Lua 是获取lua脚本中的全局变量,却怎么也调用不到,找了半天原因终于找到,如下所示加粗标红的部分
lua_State *L = luaL_newstate();
if (L == NULL)
{
return 1;
}
luaL_openlibs(L);
//lua_register(L,"TestPush", TestPush);
int ret = luaL_dofile(L,"main.lua");
if (ret)
{
printf("Lua doFile Error !\n");
}
//lua_getglobal(L, "width");
ret = lua_pcall(L, 0, 0, 0);
lua_getglobal(L, "width");//当调用lua脚本中的全局变量时必须放在lua_pcall后面
int width = lua_tonumber(L, -1);
printf("width = %d\n", width);
lua_pop(L, 1);
//无参
lua_getglobal(L, "ruler");//当调用lua脚本中的函数时必须放在lua_pcall前面
ret = lua_pcall(L, 0, 0, 0);
if (ret)
{
printf("pcall error \n");
}
//有参
lua_getglobal(L,"add");
lua_pushnumber(L, 1);
lua_pushnumber(L, 2);
ret = lua_pcall(L,2,1,0);
if (ret)
{
printf("pcall error \n");
}
if (lua_isnumber(L,-1))
{
int result = lua_tonumber(L, -1);//先分出来再调用
printf("the result is :%d", result);//使用printf必须先调用后打印,cout可以直接调用
}
lua_close(L);
getchar();
脚本如下:
function ruler()
print("this is some thing need to tell you !!!");
end
function add(a,b)
return a+b;
end
width = 2019