C / C ++:lua_rawget()与__index

时间:2014-08-23 22:23:05

标签: lua lua-table

我不理解什么?我想在__index函数中返回原始值。请参阅下面的代码。

int getValue(lua_State *L)
{
  if ( !lua_istable(L, 1) )
    return 0; // return nil

  int typ = lua_type(L, 2);
  if (typ == LUA_TSTRING)
  {
    lua_pushstring( L, lua_tostring(L, 2) );
    lua_rawget(L, 1);

    /////////////////////////////////////////////////////
    // Here I want to return the original table value..
    // BUT IT RETURNS NIL !?
    /////////////////////////////////////////////////////

    return 1;
  }
  else if (typ == LUA_TNUMBER )
  {
    int param = lua_tonumber(L, 2);
    lua_rawgeti(L, 1, param);
    return 1;
  }
  return 0;  // return nothing
}

void test1()
{
  lua_createtable(L, 0, 0);
  lua_checkstack(L, 3);

  // add some entries
  lua_pushstring(L, "MyKey1");   // key
  lua_pushstring(L, "MyValue1");  // value
  lua_settable(L, -3);
  lua_pushstring(L, "MyKey2");   // key
  lua_pushstring(L, "MyValue2");  // value
  lua_settable(L, -3);

  // create the __index function
  lua_pushcfunction(L, getValue);
  lua_setfield(L, -2, "__index");
  lua_setmetatable(L, -2);

  lua_setglobal( L, "TEST" );
}

该表不应包含整数索引条目。

用于测试的LUA声明是: " print(TEST.MyKey1)"

0 个答案:

没有答案