将库存系统移植到 C++
Coddy 面向 C++ 开发者的 Lua 课程的第 47 课,共 48 课。
挑战
中等将参考 C++ 程序移植为 Lua 模块。每行输入包含一个小写 ASCII 名称、一个冒号和一个带符号的整数增量。按名称汇总,只保留最终总和为正数的名称,按升序排序,并返回以逗号连接的 name=total 条目。如果没有符合条件的名称,则返回 empty。在 inventory.lua 中实现 inventory.aggregate(lines);由 app 负责格式化结果。所有输入行格式正确。
编辑 app.lua、inventory.lua。可见的锁定文件 main.lua 会从标准输入读取内容,将其保存为行序列,调用 app.run(lines),并打印其返回值,末尾加一个换行符。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数值输入都足够小,不会溢出。
公共 API 检查:inventory.aggregate(lines) 会返回一个新的表,其中汇总了带符号的增量,并保留总和为零的条目。空输入会得到一个空表。格式化和筛选由 app 负责。锁定的驱动程序会在调用 app.run 之前检查此行为。检查成功时不会打印任何内容。
C++17 参考
#include <iostream>
#include <map>
#include <string>
// Input: lowercase ASCII name, colon, decimal delta with optional minus sign.
// Values and totals are small enough to be represented exactly in Lua 5.1.
std::map<std::string, long long> aggregate(std::istream& input) {
std::map<std::string, long long> counts;
std::string line;
while (std::getline(input, line)) {
const auto colon = line.find(':');
counts[line.substr(0, colon)] += std::stoll(line.substr(colon + 1));
}
return counts;
}
int main() {
const auto counts = aggregate(std::cin);
bool first = true;
for (const auto& entry : counts) {
if (entry.second <= 0) continue;
if (!first) std::cout << ',';
std::cout << entry.first << '=' << entry.second;
first = false;
}
if (first) std::cout << "empty";
std::cout << '\n';
}C++ 的 map 会在首次访问时插入一个值为零的计数,并按键的顺序遍历。在 Lua 中,要区分缺失的键和已存储的零值,累加带符号的增量,然后显式排序报告中的键。这里的带符号整数由可选的 - 和后续数字组成;不会提供加号。将汇总与筛选分开,这样公共模块仍会返回总和为零或负数的条目。
亲手试试
-- 公共 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 在线编译器