1

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 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks for reply but if i put the return there what if this number is also exists in the redis? I think i am messing up in code somewhere.. What i want it to generate a random number and check for existence in redis until i get a number which doesnt exists
and by the way if i change function to local function get_random_id(id) it generates error "Script attempted to access unexisting global variable" as redis interpreter cant access global variables
Discard my first comment.. May be i am sleeping.. thanks for the response.. it works :)
@Atul If it solved your problem you may consider accepting my answer.
by the way if u can help me out with the padding also so if number is 1 i want to pad it to 0 and make it 0001
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.