简体   繁体   English

多次执行lua c ++函数会导致lua脚本失败并显示nil值

[英]Executing lua c++ Function Multiple times results in lua script failing with nil value

Lua Script Lua脚本

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

c++ code C ++代码

Init 在里面

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

update loop 更新循环

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);

first update: 1st stackdump (first line)= 'function' 2nd stackdump (last line- before pop)= 'table' 第一次更新:第一个stackdump(第一行)='function'第二个stackdump(最后一行-pop之前)='table'

second update: 1st stackdump (first line)= '' (empty) fail on lua_pcall = attempt to call a nil value 第二次更新:1st stackdump(第一行)=”(空)在lua_pcall上失败=尝试调用nil值

lua_pcall has been replaced with 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.

This will reload the file in memory if needed, otherwise call pcall 如果需要,这将在内存中重新加载文件,否则调用pcall

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM