移植 C# 库存系统
Coddy 面向 C# 开发者的 Lua 课程的第 47 课,共 48 课。
挑战
中等将参考 C# 程序移植为 Lua 模块。每行输入都由一个小写 ASCII 名称、一个冒号和一个带符号的整数增量组成。按名称汇总,只保留最终总和为正数的项目,按名称升序排序,并返回以逗号连接的 name=total 条目。如果没有剩余项目,则返回 empty。在 inventory.lua 中实现 inventory.aggregate(lines);由 app 格式化结果。所有输入行的格式都正确。
C# 参考实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
var totals=new SortedDictionary<string,long>(StringComparer.Ordinal);
string line;
while((line=Console.ReadLine())!=null){
int colon=line.IndexOf(':');
string name=line.Substring(0,colon);
long delta=long.Parse(line.Substring(colon+1),System.Globalization.CultureInfo.InvariantCulture);
totals.TryGetValue(name,out long old);
totals[name]=old+delta;
}
var rows=totals.Where(x=>x.Value>0).Select(x=>x.Key+"="+x.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)).ToArray();
Console.WriteLine(rows.Length>0 ? string.Join(",",rows) : "empty");
编辑 app.lua、inventory.lua。可见且已锁定的 main.lua 会将标准输入读入一个行序列,调用 app.run(lines),并用一个末尾换行符输出其返回值。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数字输入都足够小,不会溢出。
公共 API 检查:inventory.aggregate(lines) 返回一个包含已汇总带符号增量的新表,并保留总和为零的项目。空输入会得到一个空表。由 app 完成格式化和筛选。已锁定的驱动程序会在调用 app.run 前检查此行为。检查成功时不会打印任何内容。
亲手试试
-- 公共 API 检查
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))
面向 C# 开发者的 Lua中的所有课
自己练习: Lua 在线编译器