Protocol Buffers Lua API总结 -- 内置类型的repeated使用append() 复合类型的repeated使用add()

来源:互联网 发布:顽固软件卸载。 编辑:程序博客网 时间:2024/05/20 10:52

本文介绍的关于protocol buffers的api是基于protoc-gen-lua(see in github)这个项目的。

我的使用经验都是在开发Cocosd-x游戏的时候,lua脚本与服务器通信采用了protocol buffer,协议编译工具正是protoc-gen-lua这个插件。插件的安装过程该项目的ReadMe已经描述的很清楚,这里主要总结一下实际使用中需要注意的问题,和编译生成的pb.lua的常用API。

基本用法

1.定义一个.proto文件,假设叫做Test.proto
message Test {
    required int32 id = 1;
    optional string name = 2;
    repeated int32 ary = 3;
    message Foo {
        required int32 fid = 1;
        required string fname = 2;
    }
    repeated Foo foos = 4;
}

2.使用protoc-gen-lua插件编译proto,生成Test_pb.lua
protoc --lua_out=./ Test.proto
在项目中require(“Test_pb”)

-- 如果require失败,请参考lua中`package.path`的使用
local pb =require("Test_pb")


local test = pb.Test()
test.id = 1
test.name = "hello"
test.ary:append(1) -- 内置类型的repeated使用append()
test.ary:append(2)


local foo1 = pb.foos:add() -- 复合类型的repeated使用add()
foo1.fid = 1
foo1.fname = "foo1"
local foo2 = pb.foos:add()
foo2.fid = 2
foo2.fname = "foo2"
-- 序列化为字符串
local pb_data =test:SerializeToString()


-- 从字符串解析
local recover = pb.Test()
recover:ParseFromString(pb_data)
print(recover.id, recover.foos[1].name, recover.foos[2].na




-- 如果require失败,请参考lua中`package.path`的使用
local pb =require("Test_pb")


local test = pb.Test()
test.id = 1
test.name = "hello"
test.ary:append(1) -- 内置类型的repeated使用append()
test.ary:append(2)


local foo1 = pb.foos:add() -- 复合类型的repeated使用add()
foo1.fid = 1
foo1.fname = "foo1"
local foo2 = pb.foos:add()
foo2.fid = 2
foo2.fname = "foo2"
-- 序列化为字符串
local pb_data =test:SerializeToString()


-- 从字符串解析
local recover = pb.Test()
recover:ParseFromString(pb_data)
print(recover.id, recover.foos[1].name, recover.foos[2].na