Search code examples
luaredisstackexchange.redisjedislettuce

redis lua - eval returns wrong value when dealing with Long.MAX_VALUE


127.0.0.1:7501> eval "return {1,2,9223372036854775807}" 0
1) (integer) 1
2) (integer) 2
3) (integer) -9223372036854775808

Please help this weird behaviour. I knew that lua can only represent large number beyond 10^15 , by losing some precision. I would have expected a return value as "9.2233720368548e+18" but not a negative number.

Also fyi 127.0.0.1:7501> eval "return {1,2,tostring(9223372036854775807)}" 0
1) (integer) 1
2) (integer) 2
3) "9.2233720368548e+18"

127.0.0.1:7501> eval "return {1,2,tonumber(9223372036854775807)}" 0
1) (integer) 1
2) (integer) 2
3) (integer) -9223372036854775808


Solution

  • Taken from the doc pages (https://redis.io/commands/eval):

    Lua has a single numerical type, Lua numbers. There is no distinction between integers and floats. So we always convert Lua numbers into integer replies, removing the decimal part of the number if any. If you want to return a float from Lua you should return it as a string, exactly like Redis itself does (see for instance the ZSCORE command).

    The number you're using (~10^19) is too big to be represented in Lua as an integer, so it becomes a float. When it is translated to an integer by the Redis type conversion, it overflows and becomes an negative value.