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?
Just try math.abs(number goes here)*-1
. That’ll get the absolute (positive) value and then reverse it.
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.
Rather than putting [SOLVED] in the title, it is preferable to mark the correct answer as the solution.
Does it work the other way around ?
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
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)
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.
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
(How would I do taht?)
local number = 5
while true do
local doubleNumber = (number * 2)
number = number - doubleNumber
print(number)
break
end
Oh, just like that, thanks, I’ll edit it as soon as possible!