Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Detect if input of function is an imaginary number?

Asked by
funyun 958 Moderation Voter
9 years ago

Imaginary numbers, as in the square root of -1 and such. I'm just curious about how someone might try to approach this problem. Keep in mind that it could be i, it could be 2i, it could be 2 + 2i, etc.

1 answer

Log in to vote
1
Answered by
Unclear 1776 Moderation Voter
9 years ago

If the input is not a real number, then Lua will return a value that outputs as a string but returns true when the function type is applied on it.

However, we can take advantage of this by using tostring on the value then using tonumber on the result. If it is not a real number, then tostring will produce a string that is not equivalent to a number. tonumber applied on values that are not numbers will return nil.

The following function is the result of the facts above (and is a very elegant solution, if I do say so myself):

function isNotReal(x)
    return not tonumber(tostring(x))
end
Ad

Answer this question