Skip to content

Instantly share code, notes, and snippets.

@diegonc
Created September 13, 2018 18:36
Show Gist options
  • Save diegonc/d6af5520e8966340ccf27977220beb71 to your computer and use it in GitHub Desktop.
Save diegonc/d6af5520e8966340ccf27977220beb71 to your computer and use it in GitHub Desktop.
lua-protobuf: encode fields in sequential order
local function pbOrderedEncode(type, data)
-- Check type
if pb.type(type) == nil then
return nil, string.format("type '%s' does not exists", type)
end
-- List type fields
local typeFields = {}
for name, number, type, defval, flags in pb.fields(type) do
typeFields[name] = {
name = name,
number = number,
type = type,
flags = flags
}
end
-- List data fields
local dataFields = {}
for k,v in pairs(data) do
-- ignore fields that don't belong to the type
if typeFields[k] ~= nil then
table.insert(dataFields, k)
end
end
-- Sort data fields by number
table.sort(dataFields, function (a, b)
return typeFields[a].number < typeFields[b].number
end)
-- Encode message
local buffer = pb.buffer();
for i, fieldName in ipairs(dataFields) do
local typeField = typeFields[fieldName]
local value = data[fieldName]
-- TODO encode
end
return buffer:result(), nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment