台账:增加库存
Coddy 面向 Ruby 开发者的 Lua 课程的第 43 课,共 48 课。
通过四个相互衔接的步骤构建一个库存账本:增加数量、安全地提取、拒绝无效命令,并生成排序后的审计报告。在使用独立的 Lua 模块、表状态和显式冒号调用的同时,迁移 Ruby 对象组合的做法。保持稳定的文件布局和现有 API,除非后续任务明确要求更改。锁定的驱动程序会先检查模块行为,再运行应用程序。
挑战
中等在四节课中构建一个库存账本。文件布局保持固定:app 负责协调,inventory 管理库存,parser 解析命令,report 格式化输出。在这一步中,每行输入都是 ADD name quantity,其中名称由小写 ASCII 字符组成,数量为非负整数。将重复名称的数量累加;即使添加数量为零,也要创建对应名称的库存条目。返回 distinctNames:totalUnits。空输入返回 0:0。在 inventory.lua 中实现 Inventory.new 和 Inventory:apply。其他模块已提供。
编辑 app.lua、inventory.lua、parser.lua、report.lua。可见的锁定文件 main.lua 会将标准输入读入一个行序列,调用 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))
面向 Ruby 开发者的 Lua中的所有课
自己练习: Lua 在线编译器