Records and Map Traversal
Lesson 12 of 29 in Coddy's Lua for Luau Developers course.
A Luau dictionary annotation such as {[string]: number} describes a table but does not sort its keys. Lua 5.1 keeps the same table representation after the annotation is removed. Convert direct table traversal to pairs for map entries. When producing deterministic text, gather the keys into a dense sequence, sort that sequence, then read each corresponding value. A nil assignment removes a field in both languages, while false remains a stored value. Never use the sequence length operator to count arbitrary dictionary keys. The task replaces repeated keys, then counts keys and sums their current values.
Luau
local counts: {[string]: number} = {pen=2, book=3}
local total = 0
for _, n in counts do total += n end
print(total)Lua 5.1
local counts = {pen=2, book=3}
local total = 0
for _, n in pairs(counts) do total = total + n end
print(total)Porting trap
Generalized iteration and pairs do not promise alphabetical order. A correct sum can ignore order; a formatted report usually cannot.
Challenge
EasyInput lines are name=integer with nonempty ASCII names containing only lowercase letters. Later occurrences replace earlier values. Return keyCount:valueSum. Empty input returns 0:0.
Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for Luau Developers
3Collections and Libraries
Table Library PortingRecords and Map TraversalClone and Shared ReferencesRecap: Count InventoryModules and Host BoundariesProtected Calls and TypesPractice on your own: Online Lua compiler