【发布时间】:2010-02-27 02:57:02
【问题描述】:
我将 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)
我只能在执行此操作时调用 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);
但它给了我这个:
hello
stackoverflow!!
我想要这个:
stackoverflow!
这是我的 lua 脚本:
print("hello");
function bar()
print("stackoverflow!");
end
【问题讨论】:
-
由于您必须运行脚本才能让 Lua 虚拟机看到它,就像 Etan 指示的那样,您必须将
function bar()提取到另一个文件并运行该文件。