c - Lua - pcall "entry point"

标签 c lua

我正在加载 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/

相关文章:

visual-c++ - 编译过程

c++ - lua_sethook 是否在已注册的 C 函数中触发?

java - 用C和JAVA实现FUSE

c - SIGSEGV 不能被 sigaction 捕获两次

lua - 如何使用 Lua 读取 16 位 png?

Lua添加错误

c - 试图在 VS 2010 中使用 '#include <stdbool.h>'

c - 在c编程中获取二维数组内3x4矩阵的总分、平均分、最大分和最小分

C 数组算术和指针

arrays - 如何将函数的所有结果存储到 Lua 中的单个变量中?