Port a PHP Inventory
Lesson 47 of 48 in Coddy's Lua for PHP Developers course.
Challenge
MediumPort the reference PHP program into Lua modules. Each input line is a lowercase ASCII name, a colon, and an integer delta written as digits with an optional leading minus (no plus sign). 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.
PHP reference
<?php
function aggregate(array $lines): array {
$counts = [];
foreach ($lines as $line) {
[$name, $delta] = explode(":", $line);
$counts[$name] = ($counts[$name] ?? 0) + (int) $delta;
}
return $counts;
}
$lines = [];
while (($line = fgets(STDIN)) !== false) {
$lines[] = rtrim($line, "\r\n");
}
$counts = aggregate($lines);
ksort($counts, SORT_STRING);
$rows = [];
foreach ($counts as $name => $total) {
if ($total > 0) { $rows[] = $name . "=" . $total; }
}
echo $rows ? implode(",", $rows) : "empty";
echo "\n";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.
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 PHP Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Lua compiler