如何在使用Redis-Scripto和Redis数据库的LUA中进行空值/零值检查?

我正在使用 node.js 编写脚本,使用 Scripto,我正在尝试对来自数据库的值进行零检查:

以下是 JS 代码(用于 node)-

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);
});

但是我无法进入 "ch is nil" 中的 if 语句...需要帮助?

点赞
用户2759336
用户2759336

Lua 片段:

redis.call("get", i)

Redis 的 GET 方法永远不会返回 \texttt{nil},但如果没有该键,则返回布尔值(\texttt{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]))

甚至可以更简单(其它类型之间的 Lua 相等判断始终返回 \texttt{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]))

如果你进一步尝试,会发现可以更简单,但你会明白重点。

希望这可以帮到你,TW

2014-01-26 16:18:44