lua number & protobuf int32 int64 repeated issue: Value out of range

LUA 本身的number 支持范围

大家知道 LUA里面只有number 类型,那么number类型的范围是多少呢:[-math.pow(2, 1023) , math.pow(2, 1023)]

>Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
>return math.pow(2, 1024)
inf
> return math.pow(2, 1023)
8.9884656743116e+307
> return -math.pow(2, 1023)
-8.9884656743116e+307
> return -math.pow(2, 1024)
-inf
> return math.pow(2, 1024)
inf

那么精确的整型表达又是多少呢:math.pow(2, 53)
答案在这:http://lua-users.org/wiki/NumbersTutorial

> return string.format("%020d", -math.pow(2, 53))
-0009007199254740992
> return string.format("%020d", math.pow(2, 53))
00009007199254740992

Protobuf int 的类型有int32、int64

protobuf int32的取值范围是math.pow(2, 31) = 2147483648
protobuf int64的取值范围是math.pow(2, 63) = 9223372036854775807

但是上文中提到lua里面精确的整型的范围是math.pow(2, 53) = 9007199254740992
所以大家在使用LUA中int64的注意一下,别超过9007199254740992
但是大家需要注意一下,如果大家使用大牛 林卓毅 的protoc-gen-lua
GitHub - sean-lin/protoc-gen-lua: Google's Protocol Buffers project, ported to Lua

举个例子,大家看一下下面的message
如果coin大于231,小于253,使用protoc-gen-lua可以解析出来,但是如果repeated betNums里面如果有一个数大于2^31那么就会导致Value out of range,大家可以参考一下:
protobuf/type_checkers.lua:Int32ValueChecker 函数
protobuf/containers.lua:append 函数

message Info { 
    required string id = 1; 
    required int64 coin = 2; 
    repeated int64 betNums = 3;
}

所以在使用protoc-gen-lua repeated int64 参数的时候不要超过math.pow(2, 31) = 2147483648

ps: 如果非要使用repeated int64 超过2147483648,大家可以添加Int64ValueChecker,但是取值范围不要超过math.pow(2, 53)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值