[英]Lua script with C++ : attempt to index global 'io' (a nil value)
我打算用lua fo AI寫一個程序,所以我試着讓它一起工作。 但是當我嘗試從我的cpp文件加載lua腳本時,我收到此錯誤消息:
-- toto.lua:1: attempt to index global 'io' (a nil value)
這是我的lua腳本:
io.write("Running ", _VERSION, "\\n")
這是我的cpp文件:
void report_errors(lua_State *L, int status)
{
if ( status!=0 ) {
std::cerr << "-- " << lua_tostring(L, -1) << std::endl;
lua_pop(L, 1); // remove error message
}
}
int main(int argc, char** argv)
{
for ( int n=1; n<argc; ++n ) {
const char* file = argv[n];
lua_State *L = luaL_newstate();
luaopen_io(L); // provides io.*
luaopen_base(L);
luaopen_table(L);
luaopen_string(L);
luaopen_math(L);
std::cerr << "-- Loading file: " << file << std::endl;
int s = luaL_loadfile(L, file);
if ( s==0 ) {
s = lua_pcall(L, 0, LUA_MULTRET, 0);
}
report_errors(L, s);
lua_close(L);
std::cerr << std::endl;
}
return 0;
}
非常感謝。
你不應該直接調用luaopen_ *函數。 使用luaL_openlibs或luaL_requiref代替:
luaL_requiref(L, "io", luaopen_io, 1);
這里的特殊問題是luaopen_io
沒有在_G
存儲模塊表,因此抱怨io
是nil
值。 如果你想了解血腥細節,請查看lauxlib.c中luaL_requiref的源代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.