Rob Cook


Home | GitHub | Dev.to | Donate | Contact

[3] A little bit of Lua


2026-01-06

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")

Line by line walkthrough

  1. A comment line describing the program. Remember comments are ignored by the Lua interpreter.

  2. A blank line, also ignored by the Lua interpreter.

  3. A call to io.write to display a string literal "Enter temperature in Celsius:".

  4. Reading a line of input and assigning it to the a variable called rawInput.

  5. 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.

  6. A mathematical formula to convert Celsius into Fahrenheit. Lua has a full range of mathematical operations which are listed in the next section.

  7. A call to io.write to output the temperature in Fahrenheit.

Mathematical operators

As mentioned above, Lua contains a full set of mathematical operators for you to use in your programs.

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).

Exercises

  1. Run the conversion program in the listing and enter something that isn't a number. What happens?

  2. Run the conversion program and enter a number with a decimal point in it (20.5 for example). What happens?

Answers

  1. 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.

  2. 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.

end