Joining Text

Often, you want to print a text and a number on one line, such as Coins: 120. In Lua, you join texts with two dots, ... Programmers call joining texts concatenation:

print("Sunflower" .. " " .. "Farm")
print("Coins: " .. 120)

This prints:

Sunflower Farm
Coins: 120

.. joins the values exactly as they are, without adding any spaces. You have to write the spaces yourself, inside the quotes. That's why there is a space after the colon in "Coins: ". Without it, the text and the number stick together:

print("Coins:" .. 120)

This prints:

Coins:120

A number joined to a text becomes part of the text. You can join a calculation, too. Lua calculates first and joins after, so you don't need parentheses:

print("Eggs today: " .. 7 + 5)
print("6 carrots cost " .. 6 * 5 .. " coins.")

This prints:

Eggs today: 12
6 carrots cost 30 coins.

Always write spaces around ... Next to a number, they are even required: without them, Lua reads 1..2 as a strange number and stops with the error malformed number near '1..2'. With spaces, print(1 .. 2) prints 12: the two numbers joined into a text.

Many other languages join texts with +. In Lua, + only adds numbers, so print("Coins: " + 120) ends with the error attempt to add a 'string' with a 'number': Lua can't add a text (a string) and a number.

print can also print several values at once: separate them with commas. It prints them on one line and puts a tab between them, a wide gap that lines the values up in columns:

print("Carrot", 5, "coins")
print("Pumpkin", 20, "coins")

This prints:

Carrot	5	coins
Pumpkin	20	coins

Commas are handy when you just want to see a few values quickly. For a nice sentence, use .., which lets you decide about every space. And because a comma separates values, decimal numbers must be written with a dot: print(2,5) doesn't print two and a half, but two numbers, 2 and 5, with a tab between them.

Instructions

The program in the editor prints the prices at Emma's market stall. Run it: the commas put a tab between each name and its price. Rewrite both lines with .., and add the word coins, so that the program prints:

Carrot: 5 coins
Pumpkin: 20 coins

Grandpa Joe wants to buy 4 pumpkins. Add a line that prints how much they cost together. Let Lua calculate the price as 4 * 20, and join the result with the texts, so that the program prints:

Carrot: 5 coins
Pumpkin: 20 coins
4 pumpkins: 80 coins

Grandpa Joe also takes 10 carrots. On the last line, print how much he pays for everything. Let Lua calculate it from the prices: 4 pumpkins for 20 coins each and 10 carrots for 5 coins each. The program then prints:

Carrot: 5 coins
Pumpkin: 20 coins
4 pumpkins: 80 coins
Grandpa Joe pays: 130 coins

Start programming for free

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

Or sign up with:

4/7