Port a Luau Inventory
Lesson 28 of 29 in Coddy's Lua for Luau Developers course.
Challenge
MediumPort the reference Luau program into Lua 5.1 modules. Each input line is a lowercase ASCII name, a colon, and a signed integer delta. Aggregate by name, retain only positive final totals, sort names ascending and return name=total entries joined by commas. Return empty when none remain. Implement inventory.aggregate(lines) in inventory.lua; app formats the result. All input lines are well-formed.
Luau reference
local lines: {string} = {"pen:3", "book:2", "pen:-1"} -- INPUT
local function aggregate(rows: {string}): {[string]: number}
local counts: {[string]: number} = {}
for _, row in rows do
local name, amount = row:match("^([a-z]+):(%-?%d+)$")
assert(name and amount, "expected name:delta")
local delta = tonumber(amount)
assert(delta, "expected numeric delta")
counts[name] = (counts[name] or 0) + delta
end
return counts
end
local function run(rows: {string}): string
local counts = aggregate(rows)
local names: {string} = {}
for name, count in counts do
if count <= 0 then continue end
table.insert(names, name)
end
table.sort(names)
local out: {string} = {}
for _, name in names do table.insert(out, `{name}={counts[name]}`) end
return if #out == 0 then "empty" else table.concat(out, ",")
end
print(run(lines))Edit app.lua, inventory.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.
Public API checks: inventory.aggregate(lines) returns a fresh table of summed signed deltas, retaining zero totals. Empty input yields an empty table. Formatting and filtering happen in app. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.
The complete Luau reference runs on the sample lines table. Replace that first line to try other inputs. The target driver supplies the same data from stdin. Preserve behavior while replacing Luau syntax and retaining the required module API.
Try it yourself
-- Public API checks
do
local inventory=require("inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
All lessons in Lua for Luau Developers
Practice on your own: Online Lua compiler