Lua decimal place?

I used this in other languages, but lua seems to lack this pretty useful feature.

Can one of you glorious sentences give me the lua function to get the sign of the passed number?

+3
source share
5 answers

You can check signas follows:

i = -2
if i == math.abs(i) then -- or i >= 0
   print "positive"
else
   print "negative"
end
-3
source
function math.sign(x)
   if x<0 then
     return -1
   elseif x>0 then
     return 1
   else
     return 0
   end
end
+12
source

- : - :

function sign(x)
  return x>0 and 1 or x<0 and -1 or 0
end
+7

, , 1 -1 . , , 0. . , , (x), 0. 0.

I would stick

function sign(x)
  return (x<0 and -1) or 1
end
+3
source

You can also get the sign of a number like this:

x/ math.abs(x)

I would use this only for integers, and since Lua does not distinguish ints from floats, I would not use it in Lua at all.

-1
source

Source: https://habr.com/ru/post/1715809/


All Articles