gpt4 book ai didi

lua - 如何将 Lua 字符串转换为 float

转载 作者:IT王子 更新时间:2023-10-29 05:55:23 24 4
gpt4 key购买 nike

我正在编写一个简单的 Lua 脚本来计算 Redis 2.8 中排序集 (http://redis.io/commands/#sorted_set) 的中位数。脚本如下

local cnt = redis.call("ZCARD", KEYS[1])

if cnt > 0 then
if cnt%2 > 0 then
local mid = math.floor(cnt/2)
return redis.call("ZRANGE", KEYS[1], mid, mid)
else
local mid = math.floor(cnt/2)
local vals = redis.call("ZRANGE", KEYS[1], mid-1, mid)
return (tonumber(vals[1]) + tonumber(vals[2]))/2.0
end
else
return nil
end

问题是脚本总是返回一个整数,而结果应该是一个 float 。结果是错误的。

$ redis-cli zrange floats 0 100
1) "1.1"
2) "2.1"
3) "3.1"
4) "3.4975"
5) "42.63"
6) "4.1"

$ redis-cli EVAL "$(cat median.lua)" 1 floats
(integer) 3

正确的结果应该是(3.1 + 3.4975)/2.0 == 3.298

最佳答案

来自documentation for EVAL :

Lua has a single numerical type, Lua numbers. There is no distinction between integers and floats. So we always convert Lua numbers into integer replies, removing the decimal part of the number if any. If you want to return a float from Lua you should return it as a string, exactly like Redis itself does (see for instance the ZSCORE command).

因此,您应该更新脚本以便返回 float as a string :

return tostring((tonumber(vals[1]) + tonumber(vals[2]))/2.0)

关于lua - 如何将 Lua 字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20543450/

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