mercredi 6 janvier 2016

Redis Lua Script math.random

I just came across an interesting behavior of the Lua environment in Redis:

I have a Lua script doing some simple set operations and generating a unique timestamp like id at the end of the script - to use Redis as a timestamp oracle - like this:

...
local time = redis.call('TIME')
local millis = (tonumber(time[1]) * 1000) + math.floor(tonumber(time[2]) / 1000)
local version = string.format("%.0f",mills) .. string.format("%05d", math.random(99999))

Now version is something like this: 145209287564117083 consisting of a timestamp and five random digits at the end - at least thats what I thought.

What actually happens is, that the five random digits at the end (generated by math.random(99999) are not random at all, but always the digits 17083, no matter how often the script is executed.

For me this was not a big deal (because I can append the random digits after the script returns), but I did not expect this behavior and therefore needed quite some time to find my bug.

I hope this information can save some time.




Aucun commentaire:

Enregistrer un commentaire