从 CPP 字符串创建 Lua 表。

我正在使用 Lua 脚本编码人工智能。我希望将地图推入 Lua 的堆栈中,这个地图储存在一个 std::string * 中。我向您展示:

我的 Lua 脚本(只是一个显示地图的草图):

function        runIa(x, y, map)
   table.foreach(map, print)
   return 0
end

它只在标准输出中显示“0”。

这是我填充 std::string * 的地方:

int                     AI::update()
{
  std::string           *map = new std::string[2];
  pos_x = 0;
  pos_y = 10;

  map[0] = "0101100";
  map[1] = "1101001";
  toot->getGlobal("runIa");
  toot->pushPosToScript(pos_x, pos_y);
  toot->pushMapToScript(map);
  try {
     toot->pcall(3, 1, 0);
  }
  catch (const LuaException & e){
     std::cerr << e.what() << std::endl;
  }
  return 0;
}

这就是我将其推入 Lua 堆栈的方法:

void                    Lua::pushMapToScript(std::string *map)
{
   lua_newtable(_L);

   for (unsigned int i = 0; i < 2; ++i)
   {
      lua_pushnumber(_L, i + 1);
      lua_pushstring(_L, map[i].c_str());
      lua_settable(_L, -3);
    }
 }

它对于位置很有效,但对于地图却无效。我不能在 Lua 脚本中显示存储在变量“map”中的内容。是否有人有任何想法? 非常感谢。

点赞