Redis:Lua脚本返回排序集的每个其他第n个元素

时间:2013-04-26 11:28:03

标签: lua redis

我正在尝试整理一个从Redis调用的lua脚本(通过EVAL调用),以便返回有序集合中的每个其他第n个元素(第n个是集合中的排名,而不是分数)。 / p>

很少有可用于构建的Lua脚本的在线示例,是否有人能指出我正确的方向?

2 个答案:

答案 0 :(得分:2)

local function copyNOtherElements(table, interval, startpos)

local elemno = 1
local rettab = {}

for k, v in ipairs(table) do
   if k >= startpos and (k - startpos) % interval == 0 then
      rettab[elemno] = v
      elemno = elemno + 1
   end
end

return rettab

end

抱歉格式化,在手机上打字。假设该表是基于1的数组

答案 1 :(得分:2)

对于未来的读者,将Redis添加到上一个答案中,并使用更高效的代码来迭代第N个元素:

local function zrange_pick(zset_key, step, start, stop)
    -- The next four lines can be removed along with the start/stop params if not needed as in OP Q.
    if start == nil than
        start = 0
    if end == nil than
        end = -1

    local set_by_score = redis.call('ZRANGE', zset_key, start, end)
    local result = {}
    for n = 1, #set_by_score, step do
        table.insert(result, set_by_score[n])
    end
    return result
end