Q:

Lua check if a number/value is nan

I have written a program to print a matrix after some computations and I am getting an output of nan for all elements.  I want to break a for loop as soon as the matrix's first element becomes nan to understand the problem.  How can I do this?  In the terminal, I have printed the matrix a containing nan as all elements and typed a[1][1]=="nan" and a[{{1},{1}}]=="nan" both of which return false.  Why are they not returning false and what statement should I use instead? 

A:

Your test fails because you are comparing a number with a string, "nan". 
If you are sure it's a number, the easiest way is:
if a[1][1] ~= a[1][1] then

because according to IEEE 754, a nan value is considered not equal to any value, including itself. 

A:

Two solutions:
local n = 0/0 -- nan

-- first solution
if ( tostring(n) == "nan" ) then
   print("is nan!!") 
end

-- second solution
if (n ~= n) then
   print("is nan!!") 
end

