2016-12-29 93 views
3

嗨,我试图访问从Lua发送嵌套表C. 表是:访问嵌套表来获取值

arg = 
{ 
    MagicNumber = {MagicNumber, 0},  
    ProdNum = {ProdNum, 1}, 
    LetterR = {LetterR,  0xc}, 
    Revision = {Revision, 0xd}, 
    Space1 = {Space1,  0xe}, 
    MnfctrCode = {MnfctrCode, 0xf}, 
    Hyphen1 = {Hyphen1,  0x12}, 
    ZeroCode = {ZeroCode, 0x13},  
    Hyphen2 = {Hyphen2,  0x15}, 
    MnfctrMnth = {MnfctrMnth, 0x16}, 
    MnfctrYear = {MnfctrYear, 0x18}, 
    SerialNum = {SerialNum, 0x1a}, 
    Space2 = {Space2,  0x1e}, 
    ChkSum = {ChkSum,  0x1f}, 
} 

表里面都是整数值,和表中的键是一个字符串。我的代码片段是ollows:

lua_pushnil(L); 

while(lua_next(L, -2) != 0) 
{ 
    field = lua_tostring(L, -2); 
    printf("\n %d field = %s", i, field); 
    wrData[i-1] = lua_tonumber(L,-1); 
    printf("\n data = 0x%x", wrData[i-1]); 
    lua_pop(L, -1); 
    i++; 
} 

我错过了什么,因为我值得到的回复是0x0

+1

'lua_tonumber(L,-1)'是错误的,因为你在索引'-1'有一个表,而不是一个号码(这些都是从键 - 值对从'arg'表中的值) –

+1

' lua_pop(L,-1)'是错误的:它需要弹出的时隙数量,而不是它们的位置。 – lhf

+1

感谢您的答案,我从这里得到了答案:http://stackoverflow.com/questions/27037854/lua-c-read-nested-tables – SanR

回答

1

改变此函数以适合您的需要,并用堆栈顶部的表调用它。

void luaAccess(lua_State * L)// call this function with the table on the top of the stack 
    { 
     lua_pushnil(L); 
     while(lua_next(L, -2)) 
     { 
      switch(lua_type(L, -2)) 
      { 
       case LUA_TSTRING: 
        //deal with the outer table index here 
       break; 
       //... 
       // deal with aditional index types here 
      } 
      switch(lua_type(L, -1)) 
      { 
       case LUA_TTABLE: 
        lua_pushnil(L); 
        while (lua_next) 
        { 
         switch(lua_type(L, -2)) 
         { 
          case LUA_TNUMBER: 
           // deal with the inner table index here 
          break; 
          //... 
          // deal with aditional index types here 
         } 
         switch(lua_type(L, -1)) 
         { 
          case LUA_TSTRING: 
           //deal with strings 
          break; 
          case LUA_TNUMBER 
           //deal with numbers 
          break; 
         } 
         lua_pop(L, 1); 
        } 
       //... 
       // deal with aditional index types here 
       break 
      } 
     } 
     lua_pop(L, 1); 
    } 
+0

非常感谢!这工作! – SanR

+0

@SanjanaRakhecha然后请接受答案 –