Noah
Noah

Reputation: 43

Unexpected "table index is nan" error lua

I have the line

distanceTable[ tonumber(distance) ] = obj

Which is raising a "table index is nan" error. When distance is 67.882250993909. type(distance) returns "number"

Distance is a number so why am I getting this error?

Upvotes: 1

Views: 780

Answers (1)

IS4
IS4

Reputation: 13207

As the error message says, NaN cannot be a key in a table, similarly to nil. I suppose this limitation is caused by the fact that there are many possible binary values for a NaN, and according to the IEEE standard, NaN != NaN.

Since tonumber cannot return a NaN when given a string, it must have come from distance. One of the results of the operations you used was probably undefined, and so it returned NaN. You can use distance ~= distance to check for NaN and handle it accordingly, or prevent the computation that resulted in the value.

Upvotes: 2

Related Questions