How do you make a positive number into a negative number? [SOLVED]

I’m trying to make “A” which is equivalent to 5 into -5 the variable changes so I can’t just do
A = A - 5
how would I turn a positive number negative or overwise flip the number in Roblox Lua?

5 Likes

Just try math.abs(number goes here)*-1. That’ll get the absolute (positive) value and then reverse it.

25 Likes

Even simpler.

local a = 5
a = -a

You can simply put a minus sign before any variable name to change it from positive to negative and vice versa. It’s the same as doing 0-a or a*-1 or whatever, but simpler to write.

23 Likes

Rather than putting [SOLVED] in the title, it is preferable to mark the correct answer as the solution.

4 Likes

Does it work the other way around ?

1 Like

To set a number from positive to negative:

local a = 20
print(-a) -- -20

To set a number from negative to positive:

local  a = -20
print(math.abs(a)) -- 20
8 Likes

number that gave script can be negative. Chilio’s variant is guaranteed to give negative number.

This can be used to switch a number from negative to positive, and positive to negative. Useful for switches.

local number = 1
print(math.abs(number)*-number)
1 Like

Sorry for responding so late, I’m sure this is irrelevant to you now, but just for any future readers of this thread:

Not only is this solution overcomplicated, but this only works when the variable is ±1. A much more effective solution, as provided earlier in the thread by Elttob, is just to invert the variable.

local number = 500
print(-number)

Output:
-500

This code works both ways as it is just a simple inverter.

1 Like

There’s another way of doing this except from what others have said:

local number = 5

while true do
   local doubleNumber = (number * 2)
   number = number - doubleNumber
   print(number)
   break
end

(Multiply 5 by 2 (10) and subtract it from 5 (-5))

That script will crash the game… you forgot to add a task.wait() part

Yes, sorry, I mean to add a break function at the end but I forgot :rofl::rofl::rofl:

(How would I do taht?) :rofl::rofl::rofl:

local number = 5

while true do
  local doubleNumber = (number * 2)
   number = number - doubleNumber
   print(number)
   break
end
1 Like

Oh, just like that, thanks, I’ll edit it as soon as possible!

1 Like