ygh
ygh

Reputation: 595

Redis Lua: dynamic number of keys in redis call

I'm using a lua script to get a ZINTERSTORE result. What I want is to be able to give lua a dynamic number of zsets in the call such that:

redis.pcall('ZINTERSTORE', result, n, keys[1], keys[2], keys[3], keys[4], keys[5],  'AGGREGATE', 'MAX')

becomes something like:

redis.pcall('ZINTERSTORE', result, n, dynamic_key_list, 'AGGREGATE', 'MAX')

Lua's table.getn function lets me get the size n. Problem here is that if dynamic_key_list is a list, then redis cries loud and early with:

Lua redis() command arguments must be strings or integers

I've seen this possible solution but I don't want to iterate over the table and do the redis call every time, since I could potentially have 10-15 keys and it is an overhead I can't afford. Is there another way?

Upvotes: 2

Views: 2970

Answers (1)

for_stack
for_stack

Reputation: 23021

In order to pass a lua array/table to a function that takes variable parameters, you need the unpack function.

-- put all arguments of redis.pcall into a lua array/table
local args = {'ZINTERSTORE', result, n}
for i, v in ipairs(dynamic_key_list) do
    table.insert(args, v)
end
table.insert(args, 'AGGREGATE')
table.insert(args, 'MAX')

-- unpack the table and pass to redis.pcall
redis.pcall(unpack(args))

Upvotes: 9

Related Questions