Is there a way to detect NaN and -NaN?

Viewed 1229

I want to save lua number to string and handle NaN case correctly.

Detecting any NaN is easy, x ~= x.

However, only one way which I've found to detect is it NaN or -NaN is to use tostring(x) == 'nan'. Is there a better way to do it?

2 Answers

Instead of tostring(x) == 'nan', which is not portable, you can do the comparison with the actual tostring call: tostring(x) == tostring(0/0) or tostring(x) == tostring(-(0/0)) depending on what you need. If you need to do multiple comparisons, you can save the result of tostring and reuse it.

There are more than two NaNs exist (actually, there are 2^52-1 NaNs according to IEEE-754).
Their tostring-ed representations are platform-dependent.
This is an example how to get three different NaNs (I'm using Lua 5.3 built with Visual Studio):

n = string.unpack(">d", string.pack(">d", 0/0):sub(1, -2).."@")
print(0/0, -(0/0), n) -->  -1.#IND   1.#QNAN   -1.#QNAN

So, it would be more correct to not distinguish between different variants of NaN.

Related