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
count_words(text): a table of how many times each word appears.most_common(counts): the key with the highest count.stock_value(inventory): the total ofprice * qtyover every item.