Redis 中的 Lua 函数 - 尝试将 nil 与 number 进行比较时出错

问题描述 投票:0回答:1

我有一个 Redis 集群 v7.x,有 3 个主节点,每个主节点都有一个从节点。 我定义了一个 Lua 函数如下:

local keyGet = redis.call('GET', timeSlotKey)

local currentValue = 0
if keyGet ~= nil then
    currentValue = tonumber(keyGet)
else
    currentValue = 0
end

redis.log(redis.LOG_NOTICE, currentValue)
if currentValue < 5 then
    redis.call('INCR', timeSlotKey)
    redis.call('EXPIRE', timeSlotKey, expiryDuration)
    return 1
else
    return 0
end

当我从命令行调用该函数时,它会抛出错误:

attempt to compare nil with number
位于
if currentValue < 5 then

线

这里有什么问题?如何使用Redis的GET调用的返回值?

redis lua redis-cluster
1个回答
0
投票

问题是在调用 tonumber(keyGet) 时 currentValue 设置为 nil。

摘自tonumber的lua手册:

尝试将其参数转换为数字。如果参数已经是数字或可转换为数字的字符串,则 tonumber 返回该数字;否则,返回 nil。

所以,即使 keyGet 不为 nil,无论它是什么,它仍然不能转换为数字。

在 local keyGet = redis.call(...) 之后添加一行记录 keyGet 的值

redis.log(redis.LOG_NOTICE, keyGet)

希望这能告诉您为什么 keyGet 的值不能与 tonumber 一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.