PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Jul 02 2018, 5:36 PM PST 2 min

Roblox can do mathematical calculations, much like any calculator. In Lua, there are the following arithmetic operators:

Symbol Operation Example
+ Addition 2 + 3 = 5
- Subtraction 5 - 2 = 3
* Multiplication 5 * 2 = 10
/ Division 8 / 2 = 4
- Unary Negation -(20) = -20
^ Exponentiation 5 ^ 3 = 5 * 5 * 5 = 125
% Modulus 11 % 3 = 2

Parentheses

Parentheses can be used in Lua. If you want something calculated first, put it in parentheses.

Examples

print((10 / 20) / 5)  -- Is equal to .5 / 5, which is .1
print(10 / (20 / 5))  -- Is equal to 10 / 4, which is 2.5

Following the associative properties of multiplication and addition, it does not matter how you organize the parentheses in certain instances.

Examples

print((10 + 20) + 5)  -- Is equal to 30 + 5, which is 35
print(10 + (20 + 5))  -- Is equal to 10 + 25, which is 35
print((10 * 20) * 5)  -- Is equal to 200 * 5, which is 1000
print(10 * (20 * 5))  -- Is equal to 10 * 100, which is 1000

Precedence

For the mathematic operators, Lua follows the same rules as the ones usually followed in mathematics, the ones you have been taught or will be taught at school, with the modulus operator having the same priority as multiplication and division. That means mathematic operations will be executed in the order below:

  1. Exponentiation (^)
  2. Unary Negation (-)
  3. Multiplication, division, and modulus (*, /, and %)
  4. Addition and subtraction (+ and -)

Just like in normal math, you can use parenthesis to change the order.

See Also

Tags:
  • math
  • reference
  • lua
  • coding
  • concept