我在从C调用Lua 5.2函数时遇到了问题 .
这是Lua块(名为test.lua):
function testFunction ()
print "Hello World"
end
这是C:
int iErr = 0;
//Create a lua state
lua_State *lua = luaL_newstate();
// Load io library
luaopen_io (lua);
//load the chunk we want to execute (test.lua)
iErr = luaL_loadfile(lua, "test.lua");
if (iErr == 0) {
printf("successfully loaded test.lua\n");
// Push the function name onto the stack
lua_getglobal(lua, "testFunction");
printf("called lua_getglobal. lua stack height is now %d\n", lua_gettop(lua));
//Call our function
iErr = lua_pcall(lua, 0, 0, 0);
if (iErr != 0) {
printf("Error code %i attempting to call function: '%s'\n", iErr, lua_tostring(lua, -1));
}
} else {
printf("Error loading test.lua. Error code: %s\n", lua_tostring(lua, -1));
}
lua_close (lua);
当我跟踪时,我看到它正好加载test.lua脚本(没有返回错误),然后在使用函数名称调用lua_getglobal后显示堆栈高度为3 .
但是,它在lua_pcall失败,错误代码为2:'尝试调用nil值' .
我已经阅读了很多Lua 5.2代码的例子,似乎无法看到我出错的地方 . 这看起来应该绝对有效(根据我读过的内容) .
我检查了拼写和区分大小写,这一切都匹配了 .
我误解了什么吗???
2 回答
luaL_loadfile
只是加载文件,它不会运行它 . 请尝试luaL_dofile
.您仍然会收到错误,因为
print
是在基本库中定义的,而不是在io库中定义的 . 所以请改为luaopen_base
.你需要在
lua_getglobal()
之前拨打“priming lua_pacll()
” . 请参考Calling Lua From a C Program . 整个代码应该是这样的: