In Lua, what is #INF and #IND?

谁说胖子不能爱 提交于 2021-02-06 09:13:50

问题


I'm fairly new to Lua. While testing I discovered #INF/#IND. However, I can't find a good reference that explains it.

What are #INF, #IND, and similar (such as negatives) and how do you generate and use them?


回答1:


#INF is infinite, #IND is NaN. Give it a test:

print(1/0)
print(0/0)

Output on my Windows machine:

1.#INF
-1.#IND

As there's no standard representation for these in ANSI C, you may get different result. For instance:

inf
-nan



回答2:


Expanding @YuHao already good answer.

Lua does little when converting a number to a string, since it heavily relies on the underlying C library implementation. In fact Lua print implementation calls Lua tostring which in turn (after a series of other calls) uses the lua_number2str macro, which is defined in terms of C sprintf. Thus in the end you see whatever representation for infinities and NaNs the C implementation uses (this may vary according to which compiler was used to compile Lua and which C runtime your application is linked to).




回答3:


@YuHao has already pointed out what means +/-1.#INF (+-inf) and -1.#IND (nan), so I will just add how to deal with it (which I just needed to) in Lua:

  • "inf" (+/- 1.#INF) are the higher number values that (Lua/C) can represent and the language provides that constant for you: "math.huge". So you can test a number inside Lua for +-INF; the function "isINF()" below shows how to use it.
  • "nan" (- 1.#IND) is something that can not be handled numerically: it should be a number, its not, and anything you do with it is anything but a number also. with that in mind remember that no NaN is equal to other NaN; check for NaN like the function "isNAN()" below.

local function isINF(value)
  return value == math.huge or value == -math.huge
end

local function isNAN(value)
  return value ~= value
end



来源:https://stackoverflow.com/questions/19107302/in-lua-what-is-inf-and-ind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!