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, 内容如下:

  1. syntax = "proto3";
  2. message Person
  3. {
  4. message Hand
  5. {
  6. string left = 1;
  7. string right = 2;
  8. }
  9. message Foot
  10. {
  11. string left = 1;
  12. string right = 2;
  13. }
  14. string name = 1;
  15. uint32 age = 2;
  16. Hand hand = 3;
  17. Foot foot = 4;
  18. }

使用protoc进行编译protoc Person.pb -o Person.lua后得到文件Person.lua.

运行script/test_protobuf.lua中的示例代码查看效果:

  1. local Log = require ("logging"):new()
  2.  
  3. local pb = require "protobuf"
  4.  
  5. Log:DEBUG(pb.loadfile("Person.lua"))
  6.  
  7. local pb_string = pb.encode("Person", {
  8. name = "CandyMi",
  9. age = 2^32 - 1,
  10. hand = {
  11. left = "左手",
  12. right = "右手",
  13. },
  14. foot = {
  15. left = "左脚",
  16. right = "右脚",
  17. }
  18. })
  19. Log:DEBUG(pb.tohex(pb_string))
  20.  
  21. Log:DEBUG(pb.decode("Person", pb_string))
  22.  
  23. Log:DEBUG(pb.clear("Person"))

输出结果:

  1. [candy@MacBookPro:~/core_framework] $ ./cfadmin
  2. [2019-07-17 11:34:30,549] [@script/main.lua:5] [DEBUG] : true, 240
  3. [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
  4. [2019-07-17 11:34:30,549] [@script/main.lua:21] [DEBUG] : {["age"]=4294967295, ["foot"]={["left"]="左脚", ["right"]="右脚"}, ["name"]="CandyMi", ["hand"]={["left"]="左手", ["right"]="右手"}}
  5. [2019-07-17 11:34:30,549] [@script/main.lua:23] [DEBUG] : nil