2
votes

Setup by running sadd a b c

When I execute this code against the set a keystoclear1 has a single value of "b" in it. keystoclear2 as both values in it.

local keystoclear = unpack(redis.call('smembers', KEYS[1]))

redis.call('sadd', 'keystoclear1', keystoclear)

redis.call('sadd', 'keystoclear2', unpack(redis.call('smembers', KEYS[1])))

I am by no means a lua expert, so I could just have some strange behavior here, but I would like to know what is causing it.

I tested this on both the windows and linux version of redis, with redis-cli and the stackexchange.redis client. Same behavior in all cases. This is a trivial example, I actually would like to store the results of the unpack because I need to perform several operations with it.

UPDATE: I understand the issue.

table.unpack() only returns the first element

Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as a statement, Lua discards all of its results. When we use a call as an expression, Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions.

1

1 Answers

2
votes

This case is slightly different from the one you referenced in your update. In this case unpack (may) return several elements, but you only store one and discard the rest. You can get other elements if you use local keytoclear1, keytoclear2 = ..., but it's much easier to store the table itself and unpack it as needed:

local keystoclear = redis.call('smembers', KEYS[1])
redis.call('sadd', 'keystoclear1', unpack(keystoclear))

As long as unpack is the last parameter, you'll get all the elements that are present in the table being unpacked.