问题的不相关理由 :

我在调用 Lua 时遇到错误 format :

integer overflow attempting to store -1.#IND



变量的 type(n)真的是 number ,我可以 format它作为一个字符串(即 %s ),但它不是一个数字,例如:
print(string.format("value=%s, type=%s", n, type(n))); 

NaN值返回:

value=-1.#IND, type=number



我想解决这个问题,但我不知道是谁在生成这个 NaN (Lua 没有调试器)。

所以我不得不扔很多 asserts整个代码,直到我可以确定这个间歇性的来源 NaN值(value)。

但是我找不到任何捕获它的条件,而且 Lua 没有 isnan(x) .

问题 :

我如何测试 -1.#IND 的号码在卢阿?

更新 :

我试过:
if (n ~= n) then 
   print(string.format("NaN: value=%s, type=%s", n, type(n))); 
else 
   print(string.format("value=%s, type=%s", n, type(n))); 
end; 

它打印

value=-1.#IND, number



更新二 :以防万一我错过了什么,我的实际代码是:
    if (oldValue ~= oldValue) then 
        print(string.format("Is NaN: labelNumber=%d, formatString=\"%s\", oldValue=%s (%s)", labelNumber or 0, formatString or "nil", oldValue or "nil", type(oldValue))); 
    else 
        print(string.format("Is not NaN: labelNumber=%d, formatString=\"%s\", oldValue=%s (%s)", labelNumber or 0, formatString or "nil", oldValue or "nil", type(oldValue))); 
    end; 

错误值输出:

Is not NaN: labelNumber=4, formatString="%d", oldValue=-1.#IND (number)



更新三

还在努力解决这个问题,我才注意到现实的荒谬:
function isnan(x) 
   if type(x) ~= "number" then 
       return false; --only a number can not be a number 
   end; 
 
   ... 
end; 

请您参考如下方法:

n ~= n可能会起作用(在 Mud 的回答中描述了警告),但更便携的可能是:
function isnan(n) return tostring(n) == tostring(0/0) end
那些担心被零除的人(如 Ian 的评论;虽然我在实践中没有看到过)可以使用替代版本:
function isnan(n) return tostring(n) == tostring((-1)^.5) end
全功能:

--local nanString = (tostring((-1) ^ 0.5)); --sqrt(-1) is also NaN.  
--Unfortunately,  
--  tostring((-1)^0.5))       = "-1.#IND" 
--  x = tostring((-1)^0.5))   = "0" 
--With this bug in LUA we can't use this optimization 
local function isnan(x)  
    if (x ~= x) then 
        --print(string.format("NaN: %s ~= %s", x, x)); 
        return true; --only NaNs will have the property of not being equal to themselves 
    end; 
 
    --but not all NaN's will have the property of not being equal to themselves 
 
    --only a number can not be a number 
    if type(x) ~= "number" then 
       return false;  
    end; 
 
    --fails in cultures other than en-US, and sometimes fails in enUS depending on the compiler 
--  if tostring(x) == "-1.#IND" then 
 
    --Slower, but works around the three above bugs in LUA 
    if tostring(x) == tostring((-1)^0.5) then 
        --print("NaN: x = sqrt(-1)"); 
        return true;  
    end; 
 
    --i really can't help you anymore.  
    --You're just going to have to live with the exception 
 
    return false; 
end 


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!