Parentheses with arithmetic

From GMod Wiki

Jump to: navigation, search

Parentheses in lua (and most programming languages) are used to show that you want something done separately. These are used quite a lot, so I'll cover them here.

Parentheses are the ( and ) characters. Typically, parentheses are used when you want to do something in a specific order. For example, with arithmetic:

myNumberWithoutParentheses=5/20/5     --.05 
myNumberWithParentheses=   5/(20/5)   --1.25 

So, what's the difference? Why does one become .05 and the other 1.25?

It's the order!

If you work the "myNumberWithoutParentheses" problem out... this is what you'll get.

PROBLEM: 5/20/5 5/20 = .25 .25/5 = 0.05

ANSWER: 0.05

With parentheses, however...

PROBLEM: 5/(20/5)

20/5=4 --Remember things in parentheses are solved first. 5/4=1.25

ANSWER: 1.25

So, like you can see, order matters! If you chose not to use parentheses, you would end up doing this all the time (and I see it all the time):

mass=50 volume=2402 weight=mass*volume acceleration=500/weight

Instead of this:


Note this is a very basic example. I'm using numbers so it's familiar, but you'll most likely be using variables in lua:


You can have parentheses inside of parentheses if you need to:


In the above example, first the 3056/20 part is solved, then it subtracts 1 off of what the answer is. Then that answer is multiplied by 500.

You can use parentheses to do math in an argument, too!

function myFunc(number) 
    Msg("number is "..number.."\n") 
myFunc( (20*5)-6 ) --number is 94 

Anyway, that's how you use parentheses with math in lua!

You can give it a try if you want:

function whatIsTheAnswer(num) 
    Msg("The answer is "..num.."\n") 
--No parentheses 
--Parentheses in parentheses 
whatIsTheAnswer( (500*(20/7))-200 ) 

Save it as parentheses.lua and load it up in GMod!

Yarin Kaul Icon ArrowSquare32 left.png Using the for in loop

Yarin Kaul Icon ArrowSquare32.png Back to Lua Tutorial Series

Garry's Mod Instances Yarin Kaul Icon ArrowSquare32 right.png

Personal tools
Lua Scripting