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

Per*_*son 7 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);
Run Code Online (Sandbox Code Playgroud)

但它给了我这个:

PANIC: unprotected error in call to Lua API (attempt to call a nil value)
Run Code Online (Sandbox Code Playgroud)

我这样做时只能调用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);
Run Code Online (Sandbox Code Playgroud)

但它给了我这个:

hello
stackoverflow!!
Run Code Online (Sandbox Code Playgroud)

我想要这个:

stackoverflow!
Run Code Online (Sandbox Code Playgroud)

这是我的lua脚本:

print("hello");

function bar()
 print("stackoverflow!");
end
Run Code Online (Sandbox Code Playgroud)

Eta*_*ner 13

正如在freenode上的#lua中讨论的那样,luaL_loadfile只是简单地将文件编译成可调用的块,此时文件中没有任何代码运行(包括函数定义),因此为了得到bar的定义必须调用执行块(这是luaL_dofile所做的).