Search code examples
luaprotocol-buffers

Lua serialize failing


I'm trying to use Lua to test the Serialization and Deserialization I have message_pb.lua which has below content

cat message_pb.lua
local pb = require "pb"
local message_pb = {}

pb.load([[
    syntax = "proto3";
    message Request {
        string user_id = 1;
        int32 action = 2;
    }
]])

return message_pb  -- Return module for require()

Executing this command works lua message_pb.lua

This is my test.lua file which should load message_pb and do seriazation desriazation test

local pb = require("pb")  -- Use pb module
require("message_pb")  -- Load the compiled protobuf schema

local request_data = { user_id = "user_123", action = 1 }

-- Serialize the request
local encoded = pb.encode("Request", request_data)
if not encoded then
    print("Encoding failed!")
    return
end
print("Serialized:", encoded)

-- Deserialize the request
local decoded = pb.decode("Request", encoded)
if not decoded then
    print("Decoding failed!")
    return
end

print("Deserialized:")
for k, v in pairs(decoded) do
    print(k, v)
end

when I ran test.lua it throws error

lua test.lua
lua: test.lua:7: bad argument #1 to 'encode' (type 'Request' does not exists)
stack traceback:
    [C]: in function 'pb.encode'
    test.lua:7: in main chunk
    [C]: in ?

Solution

  • Per the documentation, pb.load accepts binary schema data, returning a boolean indicating success and, if applicable, the binary offset at which it failed parsing. A quick sanity check

    local res, off = pb.load([[
        syntax = "proto3";
        message Request {
            string user_id = 1;
            int32 action = 2;
        }
    ]])
    
    print(res, off)
    

    shows the results here to be false, 6.

    Use the protoc module to compile your schema. A very cursory example:

    local pb = require "pb"
    local protoc = require "protoc"
    
    local p = protoc.new()
    
    p:load [[
        syntax = "proto3";
        message Request {
            string user_id = 1;
            int32 action = 2;
        }
    ]]
    
    print(pb.type "Request")
    
    $ lua message_pb.lua 
    .Request    Request message