redisluaspring-data-redis

Lua Set in Redis is not working as expected


I am new to Lua scripting and facing issues while creating Set in Lua. I am trying to store unique elements in Lua Set using below code but it isn't working as expected.

local function test() 
 local t1 = {11,11,22,33,33,44,55,66,77,88,99}
 local t = {}
 for i, v in ipairs(t1)
 do
  t[v] = v
 end
 return t
end

This function is supposed to return unique elements from t1 but it's returning empty array. I think I am doing something wrong but can't figure out what. Can someone help?

Read lot about Lua Sets still couldn't figure out issue. Tried running script locally in docker with different modifications/approaches but nothing helped


Solution

  • Redis converts Lua table to array reply, and you MUST ensure that your Lua table is an array, i.e. index (table key) starting with 1.

    However, in your case, t[1] is nil, and Redis takes it as an empty array.

    In order to fix the problem, you need to convert t to an array:

    -- Your original code generating table `t`
    
    -- Then convert `t` to an array.
    local res = {}
    for k, v in pairs(t) do
       res[#res + 1] = v
    end
    return res