lua_getfield 的奇怪行为

我注意到 lua_getfield() 函数有奇怪的行为。请看这段代码片段,它应该只是从栈顶的表中取一个字段:

if(lua_istable(L,-1)){
  lua_getfield(L,-1,"field_name");
  int type = lua_type(L,-1);         // 返回 LUA_TNIL
  int field_value = lua_tointeger(L,-1); // 返回 0

  lua_pop(L,1);

  // 现在让我们尝试迭代所有表字段:
  lua_pushnil(L);  // 第一个键
  while(lua_next(L, -2) != 0){
    // 使用键(在索引-2处)和值(在索引-1处)
    CString key = lua_tostring(L,-2);
    int type = lua_type(L,-1);

    if(key == "field_name"){ //
      int value = lua_tointeger(L,-1); // 返回正确的值!!!(type == LUA_TNUMBER)
      // ????? 什么鬼 ????
    }

    // 删除 'value';保留 'key' 用于下次迭代
    lua_pop(L, 1);
  }

问题是,为什么 lua_getfield() 不起作用,而 lua_next() 完美地运行? 我已经用 lua_getfield() 函数数十次了,从未出过问题,现在我正在碰我的头到我的键盘上...

敬礼 Marcin

原文链接 https://stackoverflow.com/questions/5065397

点赞
stackoverflow用户626461
stackoverflow用户626461

问题解决了。之前调用 lua_pcall 时,结果返回数量调整有问题。然而让我困惑的是,为什么 lua_getfield() 返回失败时 lua_next 却能正常工作...

2011-03-07 22:26:52