Programs don't only have to work with strings. They can use numbers as well. The following program converts the temperature in Celsius to Fahrenheit; demonstrating the use of numbers and mathematical operations on variables.
-- Celsius to Fahrenheit converter.
io.write("Enter temperature in Celsius: ")
local rawInput = io.read()
local celsius = tonumber(rawInput)
local fahrenheit = (celsius * 9 / 5) + 32
io.write("The temperature in Fahrenheit is " .. fahrenheit .. "\n")A comment line describing the program. Remember comments are ignored by the Lua interpreter.
A blank line, also ignored by the Lua interpreter.
A call to io.write to display a string literal "Enter temperature in Celsius:".
Reading a line of input and assigning it to the a variable called rawInput.
A call to tonumber to convert the string held in rawInput into a number.
This number is then assigned to a new variable called celsius.
A mathematical formula to convert Celsius into Fahrenheit. Lua has a full range of mathematical operations which are listed in the next section.
A call to io.write to output the temperature in Fahrenheit.
As mentioned above, Lua contains a full set of mathematical operators for you to use in your programs.
+ the addition operator adds two numbers together.- the subtraction operator minus one number from the other.* the multiplication operator multiplies one number by another./ the division operator divides one number by another.% the modulus operator gives the remainder of a division operation.^ the exponentiation operator raises one number to the power of another.Lets look at a simple program to demonstrate these:
-- Mathematical operators.
io.write("10 + 5 = " .. 10 + 5 .. "\n")
io.write("10 - 5 = " .. 10 - 5 .. "\n")
io.write("2 * 10 = " .. 2 * 10 .. "\n")
io.write("10 / 2 = " .. 10 / 2 .. "\n")
io.write("10 % 3 = " .. 10 % 3 .. "\n")
io.write("2 ^ 4 = " .. 2 ^ 4 .. "\n")10 + 5 = 15
10 - 5 = 5
2 * 10 = 20
10 / 2 = 5.0
10 % 3 = 1
2 ^ 4 = 16.0
As was seen in our conversion program you can apply these operators to variables
that hold a number (as our celsius variable did).
Run the conversion program in the listing and enter something that isn't a number. What happens?
Run the conversion program and enter a number with a decimal point in it (20.5 for example). What happens?
You get an error message that says attempt to perform arithmetic on a nil value (local 'celsius').
This is because the tonumber function returns a special value - nil - if it
is unable to turn its argument into a number. We will build on this behaviour in
the next lesson, and explore nil in more detail.
Lua can handle both whole numbers (those without a decimal point, called integers), and fractional numbers (those with a decimal point, called floating point numbers). Lua uses double precision floating point numbers, which are sometimes referred to using the term double.