Redis (a key-value store) supports lua scripts – it executes the script on the server. I am interacting with Redis using a java client. I am passing a byte array to lua and in lua, I would have to convert that to a int or string.
The following is the java code snippet
byte[] exclScore = ByteBuffer.allocate(8).putDouble(1.5).array();
args.add(exclScore);
args is an ArrayList of type byte[]
Following is the lua script that I tried
byteScore = table.remove(ARGV)
size = string.len(byteScore)
x = string.sub(byteScore,1,1)
local output = 0
for i = 1,size do
bit = tonumber(string.sub(byteScore,i,1))
val2 = bit * (2 ^ i)
output = output + val2
end
return output
ARGV is the table which receives all the arguments sent by the java client and the score is the last entry. I checked the type(byteScore) and it turned out to be string. tonumber() returns a nil (which is the error I get, since I multiply it by 2)
Is there anyway in which we can convert this byte array into double or string representation of that double (1.5) in lua? Note that, we cannot use any external lua libraries inside redis scripts.
Any help is appreciated. Thanks in advance.
Lua is not a low-level language. It does not know how to handle byte arrays.
In theory, you could write a binary-to-double decoder (though that would be hard since Lua 5.1 doesn’t have any bit manipulation stuff). But your time would be better spent trying to pass Lua data that is in a form Lua understands. Lua can convert strings to numbers, so you can pass Lua a string representation of that number.
Sanitize your data outside of Lua.