cocos2dx-lua采用pbc解析proto問題修正


在cocos2dx-lua中應用pbc解析protobuf協議格式發現,其對嵌套消息的解析很不友好。 經過for pairs循環檢驗發現,decode方法並沒有解析內部嵌套的子消息。

進一步檢查發現,子消息的輸出格式為table:第一個字段為子消息的名字, 第2個字段為一個奇怪的字符串(一般為子消息的第一個字段)。進行了各種嘗試,發現只要訪問一次子消息實際存在的字段,則子消息的結構自動輸出為正常。

很奇怪吧!大神的代碼總是用各種元表奇奇怪怪的實現來追求效率, 而實際游戲開發中總是需要各種通用的寫法。

如果不能對字段進行打印調試毫無疑問是沒辦法正常開發的,最后發現只要針對子消息結構調用一次decode則可以解決嵌套消息無法正常輸出的問題。需要編寫下面代碼

function decodeAll(typename, buffer)
   local ret = decode(typename, buffer, length)
   if ret then
      decodeTable(ret)
   end
   return ret
end

function decodeTable(tbl)
   for k,v in pairs(tbl) do
       if type(v) == "table" then
          --這里的xxxx請自行替換成protobuf的package
          if(type(v[1]) == "string" and string.find(v[1],"XXXXX.")) then
               local ret = decode(v[1], v[2])
               if ret then
                  tbl[k] = ret
               end
          end
          decodeTable(tbl[k])
       end
   end
end

  游戲中調用protobuf.decodeAll即可正常解析了

另外發現decode后的lua table在訪問不存在的字段會報assert, 修改下面這個方法可以解決這個問題

function _decode_type_meta:__index(key)
    local t, msg = c._env_type(P, self._CType, key)
    --local func = assert(_reader[t], key)(msg)
    local reader = _reader[t]
    local func
    if reader then
        func = reader(msg)
    else
        func = function() end
    end
    self[key] = func
    return func
end

  這樣我們就可以在游戲中比較友好的使用pbc來解析proto格式了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM