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
| 归档时间: |
|
| 查看次数: |
5500 次 |
| 最近记录: |