白泽图

  • 文章
    • Unity渲染
    • Unity项目开发
    • 工具
    • 数学
    • 算法
    • 网站搭建
    • 网络&操作系统
蒋程个人博客
互联网技术经验总结&分享
  1. 首页
  2. Unity项目开发
  3. 正文

byte[]类型在Lua中的使用注意事项

2021-06-09 2015点热度 0人点赞 0条评论

首先Lua中不存在byte[]类型,但又不属于userdata,所有的byte[]在lua中的数据类型为string (可以使用type(data)打印出来看),但是在实际使用的过程中和真正的string还是有一些区别

今天在项目中想将服务器转过来的protobuff数据序列化到本地,模拟服务器发消息,简化调试,结果确在序列化与反序列化的时候遇到了一个问题,那就是当 

local data = msg:SerializeToString()

之后把作为“字符串”的data写成文件后

    local file = assert(io.open("d:\\out.txt", "w"))
    file:write(data)
    file:close()

再使用

    local file = assert(io.open("d:\\out.txt", "r"))
    local data = file:read('*all')
    file:close()
    msg = Module_Fight_pb.SCPlayBack() --proto协议
    msg:ParseFromString(data)

进行反序列化得到一个异常:

[2021-06-09 16:17:03:3125][NET][Error]:msg process error 1204522 SCPlayBack [string "protobuf/decoder"]:272: Truncated message.
stack traceback:
[C]: in function 'error'
[string "protobuf/decoder"]:272: in function 'field_decoder'
[string "protobuf/protobuf"]:723: in function '_internal_parse'
[string "protobuf/protobuf"]:732: in function 'parse_from_string'
[string "protobuf/protobuf"]:739: in function 'ParseFromString'


解决方法如下:

修改写入方法

local file = assert(io.open("d:\\out.txt", "w"))

为

local file = assert(io.open("d:\\out.txt", "w+b"))

修改读取方法

local file = assert(io.open("d:\\out.txt", "r"))

为

local file = assert(io.open("d:\\out.txt", "r+b"))

解释:

b代表二进制,修改后读写都是处理的二进制数据,也就是说虽然byte[]数据在lua中显示类型为string,但是在处理时还是要以二进制的方式进行处理

标签: 暂无
最后更新:2021-06-09

蒋程

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

您需要 登录 之后才可以评论

COPYRIGHT © 2023 白泽图. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

登录
注册|忘记密码?