执行lua c ++函数多次导致lua脚本失败并返回nil值

时间:2014-05-02 16:49:27

标签: c++ lua

Lua Script

algdata={lua_obj1=-1,lua_obj2=-1}
return algdata

c ++代码

初​​始化

L = lua_open();
luaL_openlibs(L);
luaL_loadfile(L, "alg_script.lua");

更新循环

int result;
printstackDump(L);
lua_newtable(L);
int tableindex = 1;
lua_pushnumber(L, tableindex++);
lua_pushnumber(L, fdcur->var1);
lua_rawset(L, -3);
lua_pushnumber(L, tableindex++);
lua_pushnumber(L, fdcur->var2);
lua_rawset(L, -3);
lua_pushnumber(L, tableindex++);
lua_pushnumber(L, fdcur->var3);
lua_rawset(L, -3);

lua_setglobal(L, "data");
result = lua_pcall(L, 0, 1, 0);
if (result) {
    fprintf(stderr, "Failed to run script: %s\n", lua_tostring(L, -1));
}
ar->lua_obj1 = GetNumberFromLua(L, "lua_obj1");
ar->lua_obj2 = GetNumberFromLua(L, "lua_obj2");
ar->lua_obj3 = GetNumberFromLua(L, "lua_obj3");
printstackDump(L);
lua_pop(L, 1);

首次更新: 1st stackdump(第一行)='function' 2nd stackdump(最后一行 - pop之前)='table'

第二次更新: 1st stackdump(第一行)=''(空) 失败的lua_pcall =尝试调用零值

1 个答案:

答案 0 :(得分:-1)

lua_pcall已替换为

int luaL_dofile (lua_State *L, const char *filename);
Loads and runs the given file. It is defined as the following macro:

     (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
It returns 0 if there are no errors or 1 in case of errors.

如果需要,这将在内存中重新加载文件,否则调用pcall