2

I'm want to read and filter data from a list in redis. I want to inspect the first 4 bytes (an int32) of data in a blob to compare to an int32 I will pass in as an ARG.

I have a script started, but how can I check the first 4 bytes?

local updates = redis.call('LRANGE', KEYS[1], 0, -1)

local ret = {}
for i=1,#updates do
    -- read int32 header
    -- if header > ARGV[1] 
    ret[#ret+1] = updates[i]
end
return ret

Also, I see there is a limited set of libraries: http://redis.io/commands/EVAL#available-libraries

EDIT: Some more poking around and I'm running into issues due to how LUA stores numbers - ARGV[1] is a 8 byte string, and cannot be safely be converted into a 64 bit number. I think this is due to LUA storing everything as doubles, which only have 52 bits of precision.

EDIT: I'm accepting the answer below, but changing the question to int32. The int64 part of the problem I put into another question: Comparing signed 64 bit number using 32 bit bitwise operations in Lua

Community
  • 1
  • 1
Charles L.
  • 5,795
  • 10
  • 40
  • 60

1 Answers1

2

The Redis Lua interpreter loads struct library, so try

if struct.unpack("I8",updates) > ARGV[1] then
lhf
  • 70,581
  • 9
  • 108
  • 149
  • This seems to work only if the numbers are <52 or so bits. – Charles L. Feb 17 '16 at 23:51
  • I changed the question to be for int32s. This solution does not work when it's abstracted to 8 bytes b/c of LUA's number handling. See http://stackoverflow.com/questions/35488855/comparing-signed-64-bit-number-using-32-bit-bitwise-operations-in-lua if you want to use 64 bits. – Charles L. Feb 19 '16 at 22:11
  • @Charles, it should work in Lua 5.3 but I don't know which version of Lua Redis uses. – lhf Feb 20 '16 at 12:34
  • Redis uses Lua 5.1, which looks like it doesn't support int64s. I have tested this as well by putting in int64 numbers, and I lose the LSB values. – Charles L. Feb 21 '16 at 17:43