Lesson 7 of 8 · 9 min

Tables as dictionaries

With names instead of numbers, a table is a dictionary (Lua programmers often say "map" or "record"):

local capitals = {
  Zimbabwe = "Harare",
  Mauritius = "Port Louis",
}
print(capitals.Zimbabwe)          -- Harare
print(capitals["Mauritius"])      -- Port Louis (same thing, with a string key)
capitals.Kenya = "Nairobi"        -- add an entry
capitals.Kenya = nil              -- remove it
print(capitals.France)            -- nil: missing keys are simply nil

Use the ["..."] form when the key is in a variable, or is a word Lua reserves (like and, end).

Looping with pairs

pairs visits every key and value, in no particular order:

for country, city in pairs(capitals) do
  print(city .. " is the capital of " .. country)
end

Tables inside tables

Values can be tables too, which is how Lua represents records:

local student = { name = "Rudo", scores = {72, 85} }
print(student.scores[2])   -- 85

Finding words

text:gmatch("%a+") goes through every run of letters in a string:

for word in ("Hi there, Lua"):gmatch("%a+") do print(word) end

Your task

  1. count_words(text): a table of how many times each word appears.
  2. most_common(counts): the key with the highest count.
  3. stock_value(inventory): the total of price * qty over every item.
main.lua
local function count_words(text)
end

local function most_common(counts)
end

local function stock_value(inventory)
end

print(most_common(count_words("to be or not to be to")))

Lua 5.4 runs right here in your browser. The first run downloads about 0.4 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…