Lua decimal sign?
Question
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?
Solution
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
OTHER TIPS
function math.sign(x)
if x<0 then
return -1
elseif x>0 then
return 1
else
return 0
end
end
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
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
You can also get the sign of a number like this:
x/ math.abs(x)
I'd only use that one for integers and since Lua doesn't distinguish ints from floats, I'd not use it in Lua at all.