main.lua 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. --- 模块功能:Google ProtoBuffs 编解码
  2. -- @module pb
  3. -- @author wendal
  4. -- @release 2022.9.8
  5. -- LuaTools需要PROJECT和VERSION这两个信息
  6. PROJECT = "pbdemo"
  7. VERSION = "1.0.1"
  8. log.info("main", PROJECT, VERSION)
  9. -- sys库是标配
  10. _G.sys = require("sys")
  11. --添加硬狗防止程序卡死
  12. if wdt then
  13. wdt.init(9000)--初始化watchdog设置为9s
  14. sys.timerLoopStart(wdt.feed, 3000)--3s喂一次狗
  15. end
  16. sys.taskInit(function()
  17. sys.wait(500)
  18. if not protobuf then
  19. log.info("protobuf", "this demo need protobuf lib")
  20. return
  21. end
  22. -- 加载 pb 文件, 这个是从pbtxt 转换得到的
  23. -- 下载资源到模块时不需要下载pbtxt
  24. -- 转换命令: protoc.exe -operson.pb person.pbtxt
  25. -- protoc.exe 下载地址: https://github.com/protocolbuffers/protobuf/releases
  26. local pb_file = "/luadb/person.pb"
  27. if io.exists(pb_file) then
  28. protobuf.load(io.readFile(pb_file))
  29. sys.publish("pb_file_exists")
  30. else
  31. log.info("protobuf","Failed to load file")
  32. end
  33. local tb = {
  34. name = "wendal",
  35. id = 123,
  36. email = "abc@qq.com"
  37. }
  38. while 1 do
  39. sys.waitUntil("pb_file_exists")
  40. sys.wait(1000)
  41. -- 用 protobuf 编码数据
  42. local pbdata = protobuf.encode("Person", tb)
  43. if pbdata then
  44. -- 打印数据长度. 编码后的数据含不可见字符, toHex是方便显示
  45. log.info("protobuf", "encode", #pbdata, (pbdata:toHex()))
  46. end
  47. -- 用 json 编码数据, 用于对比大小
  48. local jdata = json.encode(tb)
  49. if jdata then
  50. log.info("json", #jdata, jdata)
  51. end
  52. -- 可见 protobuffs 比 json 节省很多空间
  53. -- 后续是演示解码
  54. local re = protobuf.decode("Person", pbdata)
  55. if re then
  56. -- 打印数据, 因为table不能直接显示, 这里转成json来显示
  57. log.info("protobuf", "decode", json.encode(re))
  58. end
  59. end
  60. end)
  61. -- 主循环, 必须加
  62. sys.run()