1
votes

Absolutely new to lua.. just started 1 hr ago :) . I want to generate randomid and make sure that key with same id doesn't exists in redis. So i have written below code in lua

local get_random_id
get_random_id = function(id)
    local id_exists = redis.call("EXISTS", id)
    if id_exists == 0 then
         return id 
    end
    local newid = randomstring(3)
    get_random_id(newid)
end

local id = randomstring(3)
local existingid = "abc"
return get_event_id(existingid) 

It works fine if i pass the key which doesn't exists in the redis it returns me a new random key. However if key exists in redis it returns me nil.

More Info: I MONITOR redis and found script is generating the random string and checking in redis but somehow it returning nil

1

1 Answers

4
votes

You are not returning the new random id from your recursive call.

Replace the line:

get_random_id(newid)

with:

return get_random_id(newid)

BTW, you can replace the definition of your function with just:

local function get_random_id(id)
    -- ... code ..
end

instead of

local get_random_id
get_random_id = function(id)
    -- ... code ..
end