Redis-Lua表作为返回值-为什么这不起作用 [英] Redis - Lua tables as return values - why is this not working

查看:228
本文介绍了Redis-Lua表作为返回值-为什么这不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过redis EVAL运行此代码时,它不会返回任何结果.知道为什么这行不通吗?

When I run this code through redis EVAL it return no 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 that value alone gets 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 a b
1) "This"
2) "is"
3) "a"
4) "bug"

推荐答案

如果您参考 Redis EVAL文档,则您可以看到Redis将Lua表转换为Redis回复所使用的规则是什么:

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表(数组)-> Redis多批量回复(截断为第一个 如果没有,则在Lua数组中为空)
  2. 带有单个ok字段的Lua表-> Redis状态回复
  3. 带有单个err字段的Lua表-> Redis错误回复
  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

因此,除了特殊情况2和3之外,Redis假设您的表是一个序列(即列表),这意味着它会读取retv[1], retv[2], ...,直到遇到nil元素为止(这里是相应的

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).

这说明了为什么在您的情况下忽略retv["test"]的原因.

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

然后返回此附加元素:

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

这篇关于Redis-Lua表作为返回值-为什么这不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆