台账:增加库存
Coddy 面向 C# 开发者的 Luau 课程的第 43 课,共 48 课。
库存账本将解析、状态和报告拆分到不同模块中。先实现增加功能,然后添加取款功能,验证格式错误的命令,并生成确定性报告。整个过程使用相同的文件。每次继续都会从你上一步的答案开始。不需要数据库或外部软件包。
挑战
中等用四节课构建库存台账。文件布局保持固定:app 负责协调,inventory 管理库存,parser 解析命令,report 格式化输出。在这一步中,每行输入都是 ADD name quantity,其中名称由小写 ASCII 字符组成,数量为非负整数。累加重复名称对应的数量;即使添加数量为 0,也要创建对应名称的库存条目。返回 distinctNames:totalUnits。空输入返回 0:0。在 inventory.luau 中实现 Inventory.new 和 Inventory:apply。其他模块已提供。
编辑 app.luau、inventory.luau、parser.luau、report.luau。可见的锁定文件 main.luau 会将 stdin 读入一个行序列,调用 app.run(lines),并在末尾添加一个换行符后打印返回值。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数字输入都足够小,不会溢出。
公共 API 检查:Inventory.new() 会创建相互独立的库存状态。apply(command) 必须接受有效的 ADD 命令,返回 true,并将数量累加到 stock[name] 中。这项共享 API 检查在四个项目驱动程序中都相同。锁定的驱动程序会在调用 app.run 之前检查此行为。检查成功时不会打印任何内容。
亲手试试
-- 公共 API 检查
do
local Inventory=require("./inventory")
local a,b=Inventory.new(),Inventory.new()
assert(a:apply({kind="ADD",name="probe",quantity=2})==true,"inventory accepts valid additions")
assert(a:apply({kind="ADD",name="probe",quantity=3})==true and a.stock.probe==5,"inventory aggregates repeated additions")
assert(next(b.stock)==nil,"inventories must own independent stock")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
面向 C# 开发者的 Luau中的所有课
自己练习: Luau 在线编译器