Redis里执行get
或hget
不存在的key或field时返回值在终端显式的是”(nil)”
127.0.0.1:6379> get notexist
(nil)
当使用lua脚本执行逻辑时,如果要判断这个值,很容易让人迷惑以为它是nil,从而导致判断不成立,实际它是一个boolean的值
127.0.0.1:6379> eval "local v=redis.call('get',KEYS[1]); return type(v)" 1 notexist
"boolean"
所以在脚本里判断获取的结果不为空,正确的方式还有判断false的情况:
local v=redis.call('hget',KEYS[1], ARGV[1]);
if (v ~= nil or (type(v) == 'boolean' and v)) then
return 'not-empty';
end
大坑!
我又试了下,貌似应该这样写
if (v) then
return ‘is not null’
end
if (not v) then
return ‘is null’
end
刀哥,Redis Lua 脚本文档中有说明的。
[Redis Lua scripting](https://redis.io/commands/eval#conversion-between-lua-and-redis-data-types):
Redis to Lua conversion table.
* Redis Nil bulk reply and Nil multi bulk reply -> Lua false boolean type
谢谢,当时没看文档