Hello developpers!
While learning scripting math was a bit of confusion for me but I got the hang of it.
Now I hope I don’t make any mistakes writing this, if so correct me.
So in this topic, I’ll be simplifying basic math.
Operators
In lua to do math we use Operators.
Operators are also used for conditionnal statements like if ... else if
.
These are the basic operators:
[+] Addition
[-] Substraction
[*] Multiplication
[/] Division
Changing a value
In lua we have different types of values. Now let’s focus on NumberValue
s.
Now for this let’s make a simple value, no need to add in anything.
So let’s add a script (doesn’t matter much where it is placed at)
So:
OurValue = 0
--OurValue is currently at a value of 0.
print(OurValue)
The Output will print zero.
If you want it to print it something like “the value is x” then just do this:
print("The value is "..OurValue)
Now the Output will print “The value is 0”.
Great!
Now let’s change the value. Without any Operators
So:
OurValue = 0
--OurValue is currently at a value of 0.
print(OurValue)
OurValue = 5
print(OurValue)
Now OurValue is 5. But how do you change for a value outside of a script?
Let’s add a NumberValue
inside of our script! Just to change it is really simple but you need to add something at the end.
So:
local Number = script.NumberValue
print(Number.Value)
--It currently has a value of 0.
Number.Value = 5
print(Number.Value)
--Now the value is 5!
It’s pretty basic. You just need to add .Value
Changing a value with operators
This is where the fun part begins!
Now we know how to change a value. But how do we change it with Operators?
Well it seems pretty weird at first sight but you’ll get the hang of it!
So Let’s be with our NumberValue
again! Now let’s do some basic math. Let’s do a simple addition of 1 + 1.
So. let’s make the value 1:
local Number = script.NumberValue
print(Number.Value)
--It currently has a value of 0.
Number.Value = 1
print(Number.Value)
--Now the value is 1!
Now that it is one, time to do the simple math of 1 + 1.
Remember our operators!
Number.Value + 1
print(Number.Value)
Wait! There’s a problem. No number is printed! How is that. Well the script reader/OutPut was confused by what we were doing.
Now if it was a person and it read the script and said it out loud it would probably say:
“Ok so Number.Value
is our value, good. + 1
, ???. What?”
Well our script reader was confused because when we said Number.Value
it thought
[Result] = + 1
You get what I’m starting to say here?
So our script reader should be reading
[Result] = [Number.Value
] + 1
So let’s fix our script!
Number.Value = Number.Value + 1
print(Number.Value)
--It will now print 2. Because 1 + 1 = 2
Now the script reader isn’t confused anymore!
And Voilà!
So that was it!
Hope you find this tutorial helpful. It is my first one.
So thanks for reading! And now, use that knowledge!
Sources:
math (roblox.com)
Operators (roblox.com)