Iterating through a Lua table from C++?

前端 未结 3 1270
忘掉有多难
忘掉有多难 2020-12-01 02:30

I\'m trying to load tables from Lua to C++ but I\'m having trouble getting it right. I\'m getting through the first iteration just fine but then at the second call to lua_ne

3条回答
  •  旧时难觅i
    2020-12-01 03:01

    Reading LUA manual lua_next you find that problems may arise on using lua_tostring on a key directly, that is you have to check the value of the key and then decide to use lua_tostring or lua_tonumber. So you could try this code:

       std::string key
       while(lua_next(L, -2) != 0){ // in your case index may not be -2, check
    
        // uses 'key' (at index -2) and 'value' (at index -1)
    
        if (lua_type(L, -2)==LUA_TSTRING){ // check if key is a string
             // you may use key.assign(lua_tostring(L,-2));
        }
        else if (lua_type(L, -2)==LUA_TNUMBER){ //or if it is a number
             // this is likely to be your case since you table level = { 1, 2, 3, }
             // don't declare field ID's
             // try:
             // sprintf(buf,"%g",lua_tonumber(L,-2));
             // key.assign(buf);
        }
        else{
            // do some other stuff
        }
        key.clear();
        lua_pop(L,1)
       }
    

    Hope it helps.

提交回复
热议问题