Arithmetic in Lua

From GMod Wiki

Revision as of 16:11, 13 February 2011 by garry :D (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Lua can do arithmetic. While you're using Lua you're going to be using it a lot, so I'll teach you how to use it.

Open Notepad.

Lets make a variable called myNumber, and set it to 0. Start out by writing this:

function whatIsMyNumber() 
    print("myNumber is "..myNumber) 
end 
 
print("Setting myNumber to 0") 
myNumber=0

Notice that we do not use quotes here! myNumber is a number, not text! We can't do math on text, so we leave the quotes off to show it's a number.

Now write the following below it so we can check it:

whatIsMyNumber()

This calls whatIsMyNumber, the function we made above, and it will tell us what myNumber is. We'll be calling it several times which is why I made a function.

So far you should have:

function whatIsMyNumber() 
    print("myNumber is "..myNumber) 
end 
 
print("Setting myNumber to 0") 
myNumber=0 
whatIsMyNumber() 

Now, move two lines down with enter and type the following:

print("Setting myNumber to 5 + 5")
myNumber=5 + 5
whatIsMyNumber() 

This is your first arithmetic in Lua. To add two numbers, you just need to do number+ number. It's that simple.

Likewise for subtraction. To subtract two numbers you just need to do number - number.

Go down two lines and write this:

print("Setting myNumber to 10 - 5") 
myNumber=10 - 5 
whatIsMyNumber() 

Multiplication and division use special symbols. Multiplication uses an asterisk (an *), the little five sided star thing. To multiply you just need to do number * number.

Like we did for the last two, go down two lines and write this:

print("Setting myNumber to 5 times 5") 
myNumber=5 * 5 
whatIsMyNumber()

Lastly, division uses a forward slash. To divide you just need to do number / number.

Like we did for the last two, go down two lines and write this:

print("Setting myNumber to 25 divided by 5") 
myNumber=25 / 5 
whatIsMyNumber() 

Now say you want to add a number to a variable, to a number you initially don't know.

print("Adding 5 to myNumber.") 
myNumber=myNumber+5
whatIsMyNumber() 

So try it out. Save the file as arith.lua and open it in Garry's Mod.


Yarin Kaul Icon ArrowSquare32 left.png Comments

Yarin Kaul Icon ArrowSquare32.png Back to Lua Tutorial Series

The for loop Yarin Kaul Icon ArrowSquare32 right.png


Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox