Menu
CoddyTech

移植 Lua 物品栏

Coddy 面向 Lua 开发者的 Luau 课程的第 34 课,共 35 课。

challenge icon

挑战

中等

将参考 Lua 程序移植到 Luau 模块中。每行输入包含一个小写 ASCII 名称、一个冒号和一个带符号整数增量。按名称进行聚合,仅保留最终总数为正数的项目,将名称按升序排序,并返回用逗号连接的 name=total 条目。如果没有任何剩余条目,则返回 empty。在 inventory.luau 中实现 inventory.aggregate(lines);app 负责格式化结果。所有输入行均格式良好。

Lua 5.1 参考

-- Lua 5.1 reference with explicit module registration.
package.preload["app"]=function()
local M = {}
function M.run(lines)
  local inventory=require("inventory")
  local counts=inventory.aggregate(lines)
  local names={}
  for name,n in pairs(counts) do if n>0 then names[#names+1]=name end end
  table.sort(names)
  local out={}
  for _,name in ipairs(names) do out[#out+1]=name .. "=" .. counts[name] end
  return #out>0 and table.concat(out,",") or "empty"
end
return M
end
package.preload["inventory"]=function()
local M={}
function M.aggregate(lines)
  local counts={}
  for _,s in ipairs(lines) do
    local name,n=s:match("^([a-z]+):(%-?%d+)$")
    counts[name]=(counts[name] or 0)+tonumber(n)
  end
  return counts
end
return M
end
-- Public API checks
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))

编辑 app.luau、inventory.luau。可见的已锁定文件 main.luau 会从标准输入读取数据并转换为行序列,调用 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))

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

自己练习: Luau 在线编译器