Menu
CoddyTech

移植 Luau 背包系统

Coddy 面向 Luau 开发者的 Lua 课程的第 28 课,共 29 课。

challenge icon

挑战

中等

将参考 Luau 程序移植到 Lua 5.1 模块中。每行输入由一个小写 ASCII 名称、一个冒号和一个带符号的整数增量组成。按名称汇总,只保留最终总计为正数的项,按名称升序排序,并返回以逗号连接的 name=total 条目。如果没有剩余项,则返回 empty。在 inventory.lua 中实现 inventory.aggregate(lines),由 app 格式化结果。所有输入行的格式都正确。

Luau 参考代码

local lines: {string} = {"pen:3", "book:2", "pen:-1"} -- INPUT
local function aggregate(rows: {string}): {[string]: number}
  local counts: {[string]: number} = {}
  for _, row in rows do
    local name, amount = row:match("^([a-z]+):(%-?%d+)$")
    assert(name and amount, "expected name:delta")
    local delta = tonumber(amount)
    assert(delta, "expected numeric delta")
    counts[name] = (counts[name] or 0) + delta
  end
  return counts
end
local function run(rows: {string}): string
  local counts = aggregate(rows)
  local names: {string} = {}
  for name, count in counts do
    if count <= 0 then continue end
    table.insert(names, name)
  end
  table.sort(names)
  local out: {string} = {}
  for _, name in names do table.insert(out, `{name}={counts[name]}`) end
  return if #out == 0 then "empty" else table.concat(out, ",")
end
print(run(lines))

编辑 app.lua、inventory.lua。可见的锁定文件 main.lua 会将标准输入读入一个行序列,调用 app.run(lines),并在末尾输出一个换行符来打印其返回值。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数字输入都足够小,不会溢出。

公共 API 检查:inventory.aggregate(lines) 会返回一个新表,其中包含汇总后的带符号增量,并保留总计为零的项。空输入会得到一个空表。格式化和筛选在 app 中进行。锁定的驱动程序会在调用 app.run 之前检查此行为。检查成功时不会打印任何内容。

完整的 Luau 参考程序会使用示例 lines 表运行。替换第一行即可尝试其他输入。目标驱动程序会从标准输入提供相同的数据。替换 Luau 语法时,请保留原有行为并实现所需的模块 API。

亲手试试

-- 公共 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))

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

自己练习: Lua 在线编译器