Lua中的基本值比较评估不起作用。

我正在尝试比较两个值,它们看起来是相等的,但仍然被评估为不同。

我做错了什么?有什么建议吗? 我添加了tonumber(),只是为了确保我没有在某个地方将其中一个转换为字符串。

--检查当前生命值和目标生命值是否不同
if tonumber( characterStatus.current[ statusColor .. "Health" ] ) ~= tonumber( characterStatus.target[ statusColor .. "Health" ] ) then
    --目前的和目标希思量不同

    if statusColor == "monster" then print( "\nMonster Amounts Differ  ~~~~~~~~~~=" .. characterStatus.current[ statusColor .. "Health" ] .. characterStatus.target[ statusColor .. "Health" ] .. "=" ) end
end

输出是“Monster Amounts Differ ~~~~~~~~~~=99=”

点赞
用户869951
用户869951

清理你的代码以减少拼写错误的风险,并打印出两个值之间的差异:

local scCurrent = tonumber(characterStatus.current[ statusColor .. "Health" ])
local scTarget  = tonumber(characterStatus.target [ statusColor .. "Health" ])
if scCurrent ~= scTarget then
    local scDiff = scCurrent - scTarget
    if statusColor == "monster" then
        print( scCurrent, scTarget, scDiff)
    end
end

你会看到两个值之间的差异。你可能需要使用 string.format 格式化输出。

2014-01-04 07:05:53
用户3125367
用户3125367

Lua 中的数值就是双精度浮点数,因此不能简单地测试任意的双精度浮点数是否相等。

http://floating-point-gui.de/errors/comparison/

2014-01-08 12:07:17