views:

308

answers:

4

I've used this in other languages, but lua seems to be lacking this rather useful function.

Could one of you nice chappies provide me a lua function to get the sign of the number passed to it?

+1  A: 

You can check for the sign like this:

i = -2
if i == math.abs(i) then -- or i >= 0
   print "positive"
else
   print "negative"
end
Nick D
Hmm. fair enough, thanks.
+7  A: 
function math.sign(x)
   if x<0 then
     return -1
   elseif x>0 then
     return 1
   else
     return 0
   end
end
lhf
I wouldn't polute the standard library namespace.
Tadeusz A. Kadłubowski
I don't think it's a mortal sin.
lhf
+1  A: 

Just in case anyone stumbles on this one:, here's my somehow shorter version:

function sign(x)
  return x>0 and 1 or x<0 and -1 or 0
end
egarcia
Could use some parentheses for the precedence-challenged, but I like it!
Twisol
A: 

I think the idea is to return 1 or -1 to represent positive or negative. I don't think you would want it to return 0. Could have disastrous effects. Imagine trying to change the sign of a value by multiplying it by sign(x) when it returns 0. Instead of changing the sign you'd change the value to 0.

I'd stick with

function sign(x)
  return (x<0 and -1) or 1
end
rv55