gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:00:21 24 4
gpt4 key购买 nike

我正在使用 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);
});

但我无法在 if 语句中进入“ch is nil”...有什么帮助吗??

最佳答案

Lua 片段:

redis.call("get", i)

Redis 的 GET 方法从不返回 nil,但如果不存在键,它会返回一个 bool 值 (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 相等性检查,总是返回 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

关于lua - 如何使用 redis-scripto 和 redis DB 在 LUA 中执行 null\nil 检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21364251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com