Parentheses with arithmetic
From GMod Wiki
m |
m (Text replace - "{{TutorialHeader}}" to "__NOTOC__") |
||
Line 1: | Line 1: | ||
- | + | __NOTOC__ | |
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 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. | ||
Latest revision as of 15:31, 10 February 2011
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:
acceleration=500/(50*2402)
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:
acceleration=500/(mass*volume)
You can have parentheses inside of parentheses if you need to:
weightlimit=500*((3056/20)-1)
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") end 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") end --No parentheses whatIsTheAnswer(50/250/25) --Parentheses whatIsTheAnswer(50/(250/25)) --Parentheses in parentheses whatIsTheAnswer( (500*(20/7))-200 )
Save it as parentheses.lua and load it up in GMod!