Converting Values

A number can also hide in a text: "12" in quotes isn't the number 12, but a text made of the characters 1 and 2. Programs get numbers as texts all the time: what someone typed on the keyboard, a line from a file, a price on a note. And print shows both the same way, so you can't tell them apart by looking:

local eggs = 12
local note = "12"
print(eggs, note)
print(type(eggs), type(note))

This prints:

12	12
number	string

The function tonumber turns a text into a number. If the text isn't a number, it returns nil:

print(tonumber("12"))
print(tonumber("2.5"))
print(tonumber(" 7 "))
print(tonumber("12 eggs"))
print(tonumber("2,5"))

This prints:

12
2.5
7
nil
nil

Spaces around the number don't matter, but anything else in the text does, even a decimal comma. Because the result can be nil, it's a good idea to check it; you'll learn how in the lesson on conditions.

The function tostring works the other way round: it turns any value into a text. You need it when you want to join a boolean or nil to a text with ..:

local barnOpen = true
print("Barn open: " .. tostring(barnOpen))
print("Pumpkins: " .. tostring(nil))

This prints:

Barn open: true
Pumpkins: nil

Numbers don't need it: .. turns them into text by itself, as in "Coins: " .. 120.

Lua can also convert a text to a number by itself, when you calculate with it:

print("10" + 5)
print("10" * "2")
print("10" .. 5)

This prints:

15
20
105

The last line doesn't calculate: .. always joins, so "10" and 5 make the text 105. Don't rely on these conversions. Such a program works only as long as the text really is a number: "ten" + 5 stops with the error attempt to add a 'string' with a 'number'. And comparisons, which you'll learn in the next lesson, don't convert at all. With tonumber, the code clearly shows that a conversion happens, and you get nil instead of an error, which you can check.

Instructions

Convert carrotsSold and carrotPrice to numbers with tonumber, multiply them, and print how much Emma earned for the carrots:

Carrots: 60 coins

On the next line, print whether Emma sold everything. Join the value of soldOut to the text with ..; it's a boolean, so you'll need tostring:

Carrots: 60 coins
Sold out: true

For the pumpkins, Emma wrote “about 3”, which isn't a number. Print what tonumber makes of pumpkinsSold, after the text "Pumpkins:" and a comma:

Carrots: 60 coins
Sold out: true
Pumpkins:	nil

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/10