Lua与C++的脚本:尝试索引全局变量'io'(一个空值)

我要使用Lua编写人工智能程序,所以我正在尝试将其与C ++一起运行。但是,当我尝试从我的cpp文件加载Lua脚本时,我收到了以下错误消息:

- toto.lua:1:尝试索引全局“io”(为空值)

以下是我的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); //删除错误消息   } }

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); //提供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;   }

谢谢。

点赞
用户577603
用户577603

你不应直接调用 luaopen_* 函数。应该使用 luaL_openlibsluaL_requiref

luaL_requiref(L, "io", luaopen_io, 1);

这里的问题在于 luaopen_io 没有将模块表存储在 _G 中,因此会出现 ionil 的投诉。如果想要了解关于这些细节的详细信息,请查看 lauxlib.c 中的 luaL_requiref 源代码。

2013-05-06 13:33:52