我正在加载 Lua 脚本:
lua_State * L = lua_open();
luaL_openlibs(L);
const char lua_script[] = "function sum(a, b) return a+b; end print(\"_lua_\")";
int load_stat = luaL_loadbuffer(L,lua_script,strlen(lua_script),lua_script);
lua_pcall(L, 0, 0, 0);
现在我可以打电话了
lua_getglobal(L,"sum");
并在C端获取结果
但是,当我调用lua_pcall
时,脚本会被执行,并导致输出“_lua_”到控制台。如果没有 lua_pcall
,我以后将无法访问 lua_getglobal
。有没有办法解决?我不想在通过 lua_getglobal
设置“入口点”函数之前调用 lua_pcall
。
最佳答案
如果您可以修改脚本,则另一种方法是将初始化代码(print
以及可能存在的其他内容)打包到一个单独的函数中,如下所示:
lua_State * L = lua_open();
luaL_openlibs(L);
const char lua_script[] = "function sum(a,b) return a+b end return function() print'_lua_' end";
int load_stat = luaL_loadbuffer(L,lua_script,strlen(lua_script),lua_script);
lua_pcall(L, 0, 1, 0); // run the string, defining the function(s)…
// also puts the returned init function onto the stack, which you could just leave
// there, save somewhere else for later use, … then do whatever you need, e.g.
/* begin other stuff */
lua_getglobal(L, "sum");
lua_pushinteger( L, 2 );
lua_pushinteger( L, 3 );
lua_pcall(L, 2, 1, 0);
printf( "2+3=%d\n", lua_tointeger(L,-1) );
lua_pop(L, 1);
/* end other stuff (keep stack balanced!) */
// and then run the init code:
lua_pcall(L, 0, 0, 0); // prints "_lua_"
现在,虽然您仍然需要运行 block 来定义函数,但其他初始化代码会作为函数返回,您可以稍后运行/使用修改后的环境/…(或者根本不运行) ,如果您的情况没有必要。)
关于c - Lua - pcall "entry point",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43399050/