Menu
Coddy logo textTech

Cast

Part of the Fundamentals section of Coddy's Lua journey — lesson 32 of 90.

To convert the input to a different type, we need to cast.

To cast a string to a number, we will write:

var = io.read()
var = tonumber(var)

Or in one line,

var = tonumber(io.read())

If the input is a number, i.e. 5, 4, 54 then var will hold a number. If the input contains an invalid number: 5ab, bb, akt, etc. then tonumber() will return nil.

Here is a table that shows how to cast to different types:

CastExplanation
tonumber()Convert to a number
tostring()Convert to a string

It is important to use the right type because it can affect the output.

Concatenating two strings will result in:

"5" .. "5" = "55"

Adding two numbers will result in:

5 + 5 = 10

challenge icon

Challenge

Beginner

In this challenge, you'll work with multiple inputs and perform calculations.

How to receive multiple inputs:

var1 = io.read()  -- First input
var2 = io.read()  -- Second input

Your task:

  1. Read the first number from input and store it in a variable
  2. Read the second number from input and store it in another variable
  3. Convert both variables to number type (for numeric calculations)
  4. Calculate the multiplication of these two numbers
  5. Print the result

Example:

If the inputs are 2 and 4.5, your program should output 9.0

Remember: Each test case contains exactly two inputs, one after the other.

Cheat sheet

Casting in Lua:

-- Convert string to number
var = tonumber(io.read())

-- Convert to string
var = tostring(io.read())

-- tonumber returns nil for invalid input
var = tonumber("abc")  -- var is nil

Important: Concatenating strings joins them, while adding numbers performs arithmetic:

"5" .. "5" = "55"  -- String concatenation
5 + 5 = 10          -- Numeric addition

Multiple inputs:

var1 = io.read()
var2 = io.read()

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals