Redis - Lua tables as return values - why is this not working

走远了吗. 提交于 2019-12-03 14:08:08

If you refer to the Redis EVAL documentation you can see what are the rules Redis uses to convert a Lua table into a Redis reply:

  1. Lua table (array) -> Redis multi bulk reply (truncated to the first nil inside the Lua array if any)
  2. Lua table with a single ok field -> Redis status reply
  3. Lua table with a single err field -> Redis error reply

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

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

If you change your code with:

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

Then this additional element gets returned:

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

Answer from @deltheil is valid.

Remember though that you can use 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}"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!