如何使用redis-scripto和redis DB在LUA中执行null \nil检查?

Avi*_*Net 3 null lua redis null-check node-redis

我正在使用scripto在node.js中编写脚本,我正在尝试对数据库中的值进行nil检查:这里是js代码(用于节点) -

var redis = require("redis");
var redisClient = redis.createClient("6379","localhost");
var Scripto = require('redis-scripto');
var scriptManager = new Scripto(redisClient);

var scripts = {
    'test':'local function test(i) '+
    'if (i==nil) then return i end '+
    'local ch = redis.call("get", i) '+
    'if (ch==nil) then return ("ch is nil") '+
    'else return "1" '+
    'end end '+
    'return (test(KEYS[1]))',
};

scriptManager.load(scripts);
scriptManager.run('test', ["someInvalidKey"], [], function(err,result){
    console.log(err || result);
});
Run Code Online (Sandbox Code Playgroud)

但在if语句中我无法进入"ch is nil" ...任何帮助?

Tw *_*ert 16

Lua片段:

redis.call("get", i)
Run Code Online (Sandbox Code Playgroud)

Redis的GET方法永远不会返回nil,但是如果没有key,它会返回一个布尔值(false).

将您的代码更改为:

local function test(i)
  if (i==nil) then 
    return 'isnil ' .. i 
  end
  local ch = redis.call("get", i)
  if (ch==nil or (type(ch) == "boolean" and not ch)) then 
    return ("ch is nil or false")
  else 
    return "isthere '" .. ch .. "'"
  end
end
return (test(KEYS[1]))
Run Code Online (Sandbox Code Playgroud)

甚至更简单(允许在不同类型之间进行Lua相等检查,总是返回false):

local function test(i)
  if (i==nil) then 
    return 'isnil ' .. i 
  end
  local ch = redis.call("get", i)
  if (ch==false) then 
    return ("ch is false")
  else 
    return "isthere '" .. ch .. "'"
  end
end
return (test(KEYS[1]))
Run Code Online (Sandbox Code Playgroud)

如果你多玩一点,你会发现你可以比它更简单,但你会明白这一点.

希望这有帮助,TW

  • 这很有趣,因为最新的 redis 文档说:“获取键的值。如果键不存在,则返回特殊值 nil”[GET key](https://redis.io/commands/get) 但我是发现这篇文章描述的相同行为...... (3认同)
  • @Nitax,这比那更微妙。在Lua内部,它是假的。但当返回给客户时,它为零。这可能与 Lua 的限制有关。恕我直言,尼尔斯并不是 Lua 最强的壮举。尽管如此,还是喜欢这门语言。--- `redis-cli get blah` (nil) `redis-cli eval 'return redis.call("get","blah")' 0` (nil) `redis-cli eval 'return tostring(redis.call) ("get","blah"))' 0` "假" (3认同)