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 writing string.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().
  • upper and lower change the case of letters, len (or #) gives the length, rep repeats a text, and reverse turns it around.
  • s:sub(i, j) gives the part from the position i to j, both included; without j, 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, or nil. Without 1, 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. #, sub and widths count bytes, upper and lower change only a to z, and utf8.len counts 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. %a doesn't know letters with accents.
  • match gives the first match, or its captures in parentheses (always texts), or nil. gmatch goes through all the matches in a for loop.
  • gsub replaces 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

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

Or sign up with:

9/9