Text
Texts in programs are called strings: characters strung together like beads on a string. You know that you write them in double quotes "…" or single quotes '…'. You can store a text in a variable like any other value, and join texts with ..:
local farm = "Sunflower Farm"
local crop = "pumpkins"
local sign = crop .. " from " .. farm
print(sign)
print(farm .. crop)This prints:
pumpkins from Sunflower Farm
Sunflower Farmpumpkins.. doesn't add any spaces. Write them into the texts yourself, as in " from ". And + doesn't join texts: "Sunflower" + "Farm" ends with the error attempt to add a 'string' with a 'string', because + only adds numbers.
A text in double quotes ends at the next double quote. If you need quotes inside it, there are two ways: put the text in the other kind of quotes, or write a backslash \ in front of the quote:
print('Emma says: "Welcome!"')
print("Emma says: \"Welcome!\"")
print("Grandpa Joe's barn")This prints:
Emma says: "Welcome!"
Emma says: "Welcome!"
Grandpa Joe's barnWithout the backslash, the text ends too early:
print("Emma says: "Welcome!"")Lua reports:
main.lua:1: ')' expected near 'Welcome'The text ended after Emma says: , and then Lua found the word Welcome where it expected the closing parenthesis.
A backslash and the character after it make an escape sequence: two characters in the code that stand for one special character in the text:
\nis a new line,\tis a tab,\"and\'are quotes,\\is one backslash.
print("Carrots\nPotatoes\tPumpkins")This prints:
Carrots
Potatoes PumpkinsThe length of a text is given by # in front of it:
local farm = "Sunflower Farm"
print(#farm)
print(#"Rex")
print(#"")This prints:
14
3
0The space counts too, and "" is an empty text, with no characters at all. Strictly speaking, # counts bytes, the small units in which the computer stores a text. A plain letter, digit, space or punctuation mark takes one byte, but a letter with an accent, such as the é in café, takes two, so #"café" is 5. You'll learn how to count such letters in the lesson on strings.
Instructions
Below, create a variable sign that joins the word Fresh, the variable crop, the word from and the variable farm, with spaces between them. Then print it:
Fresh strawberries from Sunflower FarmBelow, print Emma's invitation on two lines. Use one print with \n for the new line, and keep the quotes around her words:
Fresh strawberries from Sunflower Farm
Emma says:
"Taste one!"Finally, print how long the sign is. Get the number from the variable sign with #:
Fresh strawberries from Sunflower Farm
Emma says:
"Taste one!"
The sign is 38 characters long.Start programming for free
5/10