2
votes

I'd like to summary key values of monthly with 'hget' command.

Test Set) hmset SiteID:TotalCnt 20180101 10 20180102 2 20180103 5 20180120 10 20180131 30 20180205 20 20180210 5

I'd like to summary key values of 2018.01 So, I did..

sumkey.lua

local mon = ARGV[1]
local sumkey = 0
local forkey = ''
for i = 1,31 do
    if i < 10 then local dd = '0' .. tostring(i)
    else dd = tostring(i)
    end 
    forkey = mon .. dd
    sumkey = sumkey + redis.call('hget' , KEYS[1] , forkey)
 end
 return sumkey

ubuntu@:~$ redis-cli -n 2 --eval sumkey.lua (error) ERR Error running script (call to f_1c9d9d311f9c1e2fbb34fa81176539ad45da3b5b): @enable_strict_lua:15: user_script:8: Script attempted to access unexisting global variable 'dd'

tostring does not work.!!!

How can I summary values of key ???

3

3 Answers

3
votes

Try to declare it(dd) before the loop. The problem is that if the if statement is not satisfied, the dd variable is not defined, so it tries to find a global variable with this name.

0
votes

You have to "localize" the variable before the if ... then branch as otherwise it only stays "visible" inside that branch and after leaving the branch the value is restored to whatever it was before that:

local dd
if i < 10 then dd = '0' .. tostring(i)
else dd = tostring(i)
end

You can also convert it to one expression:

local dd = i < 10 and '0' .. tostring(i) or tostring(i)

or use format:

forkey = mon .. ("%02d"):format(i)
0
votes

I did it.

See below.

:sumkey.lua

local key, mon = KEYS[1], ARGV[1]
local subkey
local sumkey, keyval= 0

for i = 1,31 do
    if i < 10 then subkey = mon .. '0' .. tostring(i)
    else subkey = mon .. tostring(i)
    end

    keyval = tonumber(redis.call('hget',KEYS[1],subkey))

    if keyval ~= nil then
        sumkey = sumkey + keyval
    end
end

return sumkey

ubuntu@$ redis-cli -n 2 --eval sumkey.lua SiteID:TotalCnt , '201801' (integer) 57

have a great day everyone ~~!!