Port a Ruby Inventory
Lesson 47 of 48 in Coddy's Lua for Ruby Developers course.
Challenge
MediumPort this complete Ruby program into Lua modules. Each input line is a lowercase ASCII name, a colon, and a signed integer delta. All lines are well-formed and quantities and intermediate totals stay within the exact integer range of the Lua number representation. Aggregate every update before filtering. Return positive final totals as name=total entries in ascending name order, joined by commas, or empty if none remain. inventory.aggregate(lines) must return a fresh table of all summed deltas, retaining zero totals. The editable app formats and filters that table. Unlike Ruby Hash iteration, Lua pairs does not promise insertion order; sort the names explicitly.
Ruby inventory reference
def aggregate(lines)
counts = Hash.new(0)
lines.each do |line|
name, amount = line.split(":", 2)
counts[name] += Integer(amount, 10)
end
counts
end
counts = aggregate(STDIN.read.lines.map(&:chomp))
rows = counts.keys.sort.select { |name| counts[name] > 0 }
.map { |name| "#{name}=#{counts[name]}" }
puts(rows.empty? ? "empty" : rows.join(","))Edit app.lua and inventory.lua. The visible locked main.lua reads stdin into lines, checks the public API, calls app.run(lines), and prints one returned value with a final newline. Do not print diagnostics. Input is nonempty for the room task; inventory input may be empty.
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 Ruby Developers
1From Ruby to Lua
Run Lua Modulesputs to printRuby Locals and Lua ScopeRuby Integer to Lua NumberStrings as Byte SequencesRecap: Format a Receipt4Methods, Functions, Closures
Methods to FunctionsKeyword Defaults to OptionsTuples to Multiple ResultsBlocks and Captured LocalsRecap: Pricing Functions2Values and Decisions
nil Values and Missing FieldsShared Truth Ruleselsif to elseifRuby == and Table IdentityRecap: Admission Rules5Arrays and Hashes to Tables
Arrays to Dense TablesHash Records and pairsSet Membership with Keysdup and Table CopiesRecap: Count InventoryPractice on your own: Online Lua compiler