ProtoBuffer库
此库来自这里.
ProtoBuffer API
导入
local protobuf = require "protobuf"
protobuf.load(string)
读取编译完成后的protobuffer字符串
protobuf.loadfile(filename)
读取编译完成后的protobuffer文件
protobuf.encode(struct, table)
将table
按照struct
字符串定义的结构进行序列化.
protobuf.decode(struct, string)
将string
按照struct
字符串定义的格式进行反序列化.
protobuf.tohex(string)
将string
数据进行16进制格式打印.
protobuf.clear(struct)
清除struct
定义的结构体.
示例
首先定义一个标准的pb语法文件Person.pb
, 内容如下:
syntax = "proto3";
message Person
{
message Hand
{
string left = 1;
string right = 2;
}
message Foot
{
string left = 1;
string right = 2;
}
string name = 1;
uint32 age = 2;
Hand hand = 3;
Foot foot = 4;
}
使用protoc
进行编译protoc Person.pb -o Person.lua
后得到文件Person.lua
.
运行script/test_protobuf.lua
中的示例代码查看效果:
local Log = require ("logging"):new()
local pb = require "protobuf"
Log:DEBUG(pb.loadfile("Person.lua"))
local pb_string = pb.encode("Person", {
name = "CandyMi",
age = 2^32 - 1,
hand = {
left = "左手",
right = "右手",
},
foot = {
left = "左脚",
right = "右脚",
}
})
Log:DEBUG(pb.tohex(pb_string))
Log:DEBUG(pb.decode("Person", pb_string))
Log:DEBUG(pb.clear("Person"))
输出结果:
[candy@MacBookPro:~/core_framework] $ ./cfadmin
[2019-07-17 11:34:30,549] [@script/main.lua:5] [DEBUG] : true, 240
[2019-07-17 11:34:30,549] [@script/main.lua:19] [DEBUG] : 10 FF FF FF FF 0F 22 10 0A 06 E5 B7 A6 E8 84 9A 12 06 E5 8F B3 E8 84 9A 0A 07 43 61 6E 64 79 4D 69 1A 10 0A 06 E5 B7 A6 E6 89 8B 12 06 E5 8F B3 E6 89 8B
[2019-07-17 11:34:30,549] [@script/main.lua:21] [DEBUG] : {["age"]=4294967295, ["foot"]={["left"]="左脚", ["right"]="右脚"}, ["name"]="CandyMi", ["hand"]={["left"]="左手", ["right"]="右手"}}
[2019-07-17 11:34:30,549] [@script/main.lua:23] [DEBUG] : nil