Menu
CoddyTech

账本:添加股票

Coddy 面向 Python 开发者的 Luau 课程的第 43 课,共 48 课。

股票账本将解析、状态和报告拆分为不同模块。首先实现添加功能,然后添加提取功能,验证格式错误的命令,并生成确定性的报告。在整个过程中保持使用相同的文件。每个后续步骤都基于你之前的解决方案。不需要数据库或外部包。

challenge icon

挑战

中等

通过四节课构建一个库存账本。文件布局保持固定:app 负责协调,inventory 拥有库存,parser 解码命令,report 格式化输出。在此步骤中,每个输入行都是 ADD name quantity,其中包含小写 ASCII 名称和非负整数数量。累加重复出现的名称;增加零依然会创建一个带名称的库存条目。返回 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))

面向 Python 开发者的 Luau中的所有课

自己练习: Luau 在线编译器