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?
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?
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
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