Redis Tables - Lua as Return Values ​​- Why It Doesn't Work

When I run this code through redis EVAL, it does not return any results. Any idea why this is not working?

redis-cli EVAL "$(cat bug.lua)" 0 

bug.lua

 local retv = {} retv["test"] = 1000 return retv 

If I initialize the table, this value will be printed.

 $ cat bug.lua --!/usr/bin/env lua local retv = {"This", "is", "a", "bug" } retv["test"] = 1000 return retv $ redis-cli EVAL "$(cat bug.lua)" 2 ab 1) "This" 2) "is" 3) "a" 4) "bug" 
+6
source share
2 answers

If you refer to the Redis EVAL documentation, you can see what rules Redis uses to convert the Lua table to a Redis response:

  • Lua table (array) -> Redis multi bulk reply ( truncated to the first nil inside the Lua array, if any )
  • Lua table with one ok field -> Redis status message
  • Lua table with one err field -> Redis response error

Therefore, except in special cases 2 and 3, Redis assumes that your table is a sequence (that is, a list), which means that it reads retv[1], retv[2], ... until it encounters the nil element (here is the corresponding source code ).

This explains why retv["test"] ignored in your case.

If you change your code to:

 local retv = {"This", "is", "a", "bug" } retv[5] = 1000 return retv 

Then this extra element is returned:

 1) "This" 2) "is" 3) "a" 4) "bug" 5) (integer) 1000 
+7
source

The answer from @deltheil is valid.

Remember that you can use the cjson library to pack tables and pass them to consumers.

Your lua file:

 local retv = {"This", "is", "a", "bug" } retv["test"] = 1000 return cjson.encode(retv) 

Command:

 redis-cli EVAL "$(cat bug.lua)" 0 

Result:

 "{\"1\":\"This\",\"2\":\"is\",\"3\":\"a\",\"4\":\"bug\",\"test\":1000}" 
+3
source

Source: https://habr.com/ru/post/971029/


All Articles