5
votes

I'm writing a LUA script in redis to return the result of the division of two keys (XXX_COUNT and XXX_TOTAL) already stored or 0 if any of the key doesn't exists. The code for the script is as follows:

    local count = redis.call("GET", KEYS[1]..'_COUNT')
    local total = redis.call("GET", KEYS[1]..'_TOTAL')
    if not count or not total then
        return 0
    else
        return tonumber(total)/tonumber(count)
    end

The problem is that when the script returns "tonumber(total)/tonumber(count)" it's value is always 0, already checked the keys and they have non zero values stored as strings in redis. What is wrong with this script?

Thanks in advance!

1
Use a print( total, count ) and check what it shows. - hjpotter92

1 Answers

4
votes

I've found the solution, I needed to convert the result to string before returning it:

    local count = redis.call("GET", KEYS[1]..'_COUNT')
    local total = redis.call("GET", KEYS[1]..'_TOTAL')
    if not count or not total then
        return 0
    else
        local avg = tonumber(total)/tonumber(count)
        return tostring(avg)
    end

Hope it helps somebody!