Port an Inventory
Lesson 47 of 48 in Coddy's Luau for Go Developers course.
Challenge
MediumPort the reference Go program into Luau 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.luau; app formats the result. All input lines are well-formed.
Go reference
package main
import("fmt";"io";"os";"sort";"strconv";"strings")
func main(){
raw,err:=io.ReadAll(os.Stdin); if err!=nil {panic(err)}
totals:=map[string]int64{}
text:=strings.TrimSuffix(string(raw),"\n")
if len(raw)>0 {for _,line:=range strings.Split(text,"\n") {
parts:=strings.SplitN(line,":",2)
delta,err:=strconv.ParseInt(parts[1],10,64); if err!=nil {panic(err)}
totals[parts[0]]+=delta
}}
keys:=[]string{}; for name,total:=range totals {if total>0 {keys=append(keys,name)}}
sort.Strings(keys)
rows:=[]string{}; for _,name:=range keys {rows=append(rows,name+"="+strconv.FormatInt(totals[name],10))}
if len(rows)==0 {fmt.Println("empty")} else {fmt.Println(strings.Join(rows,","))}
}
Edit app.luau, inventory.luau. The visible locked main.luau 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 Luau for Go Developers
1First Luau Programs
Run Luau 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
Missing Fields and OptionalsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Luau compiler