Menu
CoddyTech

Port GDScript Inventory

Lesson 47 of 48 in Coddy's Lua for GDScript Developers course.

challenge icon

Challenge

Medium

Port the reference GDScript program into Lua 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.

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.

GDScript 4 reference

Run as a headless script. The entry reads standard input, prints one result and quits. Preserve the domain behavior when moving it into the supplied Lua modules.

extends SceneTree

# Input lines are lowercase names followed by a colon and a signed integer.
# A blank read marks EOF because the input contract excludes blank lines.
func _init() -> void:
	var counts: Dictionary = {}
	while true:
		var line := OS.read_string_from_stdin()
		if line.is_empty():
			break
		var parts := line.split(":")
		var item := parts[0]
		counts[item] = counts.get(item, 0) + int(parts[1])
	var names: Array = counts.keys()
	names.sort()
	var rows: PackedStringArray = []
	for item in names:
		if counts[item] > 0:
			rows.append("%s=%d" % [item, counts[item]])
	print(",".join(rows) if not rows.is_empty() else "empty")
	quit()

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 GDScript Developers

Practice on your own: Online Lua compiler