Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在不执行脚本的情况下调用Lua函数_C++_C_Lua - Fatal编程技术网

C++ 在不执行脚本的情况下调用Lua函数

C++ 在不执行脚本的情况下调用Lua函数,c++,c,lua,C++,C,Lua,我正在将Lua嵌入C/C++应用程序中。有没有办法在不首先执行整个脚本的情况下从C/C++调用Lua函数 我试过这样做: //call lua script from C/C++ program luaL_loadfile(L,"hello.lua"); //call lua function from C/C++ program lua_getglobal(L,"bar"); lua_call(L,0,0); 但它给了我这个: PANIC: unprotected error in cal

我正在将Lua嵌入C/C++应用程序中。有没有办法在不首先执行整个脚本的情况下从C/C++调用Lua函数

我试过这样做:

//call lua script from C/C++ program
luaL_loadfile(L,"hello.lua");

//call lua function from C/C++ program
lua_getglobal(L,"bar");
lua_call(L,0,0);
但它给了我这个:

PANIC: unprotected error in call to Lua API (attempt to call a nil value)
hello
stackoverflow!!
我只能在执行以下操作时调用bar():

//call lua script from C/C++ program
luaL_dofile(L,"hello.lua");  //this executes the script once, which I don't like

//call lua function from C/C++ program
lua_getglobal(L,"bar");
lua_call(L,0,0);
但它给了我这个:

PANIC: unprotected error in call to Lua API (attempt to call a nil value)
hello
stackoverflow!!
我想要这个:

stackoverflow!
这是我的lua脚本:

print("hello");

function bar()
 print("stackoverflow!");
end

正如刚才在#lua on freenode luaL_loadfile中所讨论的那样,loadfile只是将文件编译成一个可调用的块,在这一点上,文件中的任何代码都没有运行(包括函数定义),因此为了获得执行块的bar定义,必须调用该块(这就是luaL#u dofile所做的).

发现必须运行脚本才能调用函数。

一个可能的解决方案/破解(请记住,我目前无法测试此功能)


在LUA代码的顶部插入一个伪“return;”行

  • 将文件加载到字符串中(就像准备使用
    luaL\u loadstring()
  • 现在,使用
    printf\u s(“return;\r\n%s”,[指向保存实际LUA代码的字符串的指针])应该很简单了。
  • 现在您可以
    luaL\u loadstring()
    连接的字符串
代码仍将执行,但在它实际到达任何有作用的东西之前,它应该被切断(在您的
打印(“hello”);
示例中,打印行将无法到达)。它应该仍然更新了所有函数原型的列表,您现在应该能够使用
lua_get()
引用函数



注意:对于那些不知道“\r\n”的人,是表示Windows操作系统上换行符的转义码,必须是那些斜杠。。。IE:THIS\r\n而不是THIS/r/n

我是在聊天中问这个问题的人:PI认为你是,但认为我无论如何都会明确引用,以防万一。因为你必须运行脚本才能让Lua VM看到它,就像Etan指出的那样,你必须提取出
函数栏()
转到其他文件,然后运行该文件。