Summary
In this lesson, you learned that:
- A text is a string. Its functions are in the table
string, and you usually call them as methods, with a colon:crop:upper()is a short way of writingstring.upper(crop). A text written in the code needs parentheses:("="):rep(10). - String functions never change a text; they give a new one, which you have to store or use:
crop = crop:upper(). upperandlowerchange the case of letters,len(or#) gives the length,reprepeats a text, andreverseturns it around.s:sub(i, j)gives the part from the positionitoj, both included; withoutj, to the end. Negative positions count from the end:s:sub(-3)is the last three characters.s:find(text, 1, true)gives the positions where a text starts and ends, ornil. Without1, true, the text is a pattern.("%-10s %6.2f"):format(name, kg)fills values up to a width: with a minus, the value goes to the left, without it to the right.%%is a percent sign.- Texts are bytes, and a letter with an accent takes two.
#,suband widths count bytes,upperandlowerchange only a to z, andutf8.lencounts characters. Pad with(" "):rep(width - utf8.len(text)). - Patterns have classes,
%d,%a,%w,%s(capital letters for the opposite) and.for any character; sets such as[^,];+,*and-for repeating;^and$for the start and the end; and%before a magic character.%adoesn't know letters with accents. matchgives the first match, or its captures in parentheses (always texts), ornil.gmatchgoes through all the matches in aforloop.gsubreplaces every match and returns two values, the new text and the count:print((s:gsub("a", "b")))prints only the text.
In the next lesson, on objects and metatables, you'll find out how the colon really works and give your own tables methods. But first, try out what you know on the day's sales at the market.
Instructions
Go through sales with gmatch and draw a bar chart: for each crop, its name filled up with spaces to 14 characters (count them with utf8.len), then one # for every piece sold. Watch the spaces after some of the commas: they mustn't get into the names. And the ñ mustn't cause any trouble either.
pumpkins ###
carrots #######
jalapeños #####
strawberries ####Below the chart, print how many pieces Emma sold in total, and which crop sold the most: Total: 19, best seller: carrots.
Start programming for free
9/9