Nathan Goings
Nathan Goings

Reputation: 1164

In Lua, what is #INF and #IND?

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?

Upvotes: 8

Views: 15470

Answers (3)

Brandt
Brandt

Reputation: 5659

@YuHao has already answered what the OP has asked: what does +/-1.#INF (+-inf) and -1.#IND (NaN) mean. What I want to do here is just to add to the discussion by expanding on how to check them (which I just needed and learned to):

  • inf (+/-1.#INF) are the highest numbers(+/-) Lua can represent, and the Language provides such value(s) through math.huge. You can test if a number is +/-INF:
local function isINF(value)
  return value == math.huge or value == -math.huge
end
  • NaN (-1.#IND) is something that can not be handled numerically, the result of any operation involving it is also Not-a-Number(*). Long-story-short: if a value is NaN, comparing it against itself will (always) be False. The function below implements the simplest way for checking if a value is NaN:
local function isNAN(value)
  return value ~= value
end

(*): NaN is formally defined in the IEEE754 standard.

Upvotes: 7

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).

Upvotes: 7

Yu Hao
Yu Hao

Reputation: 122463

#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

Upvotes: 12

Related Questions