【问题标题】:Lua script with C++ : attempt to index global 'io' (a nil value)使用 C++ 的 Lua 脚本:尝试索引全局“io”(零值)
【发布时间】:2013-05-06 12:54:46
【问题描述】:

我打算使用 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;
  }

非常感谢。

【问题讨论】:

  • 代码为它运行的每个文件创建一个单独的 Lua 状态。这将防止不同的文件进行通信。这可能不是你想要的。

标签: c++ io lua


【解决方案1】:

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

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

这里的特殊问题是luaopen_io 没有将模块表存储在_G 中,因此抱怨ionil 值。如果您想了解详细信息,请查看 lauaL_requiref 的 lauaL_requiref 源代码。

【讨论】:

  • 谢谢,它现在可以正常工作了,我改用 luaL_openlibs。我会记住你的建议!
  • 它有帮助。您能否详细说明为什么 luaopen_* 不起作用?这是您在他们的文档中看到的第一件事
  • @VladLazarenko luaopen_* 函数只是在堆栈顶部创建一个表(主要包含函数)。缺少的是将该表与名称相关联,以便可以从 Lua 中访问它并将其注册到模块加载机制。然而,这两个步骤对所有库都相同。将 luaopen_* 函数视为库编写器为设置该特定库而提供的功能。它的目标不是进行完整的库加载,而是提供 luaL_requiref 执行加载所需的信息。
  • @ComicSansMS:知道了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 2014-01-21
  • 2014-01-26
  • 2017-01-10
  • 1970-01-01
相关资源
最近更新 更多