Menu
CoddyTech

移植物品栏

Coddy 面向 GDScript 开发者的 Luau 课程的第 47 课,共 48 课。

challenge icon

挑战

中等

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

GDScript 参考程序

extends SceneTree
func inventory(lines):
    var counts = {}
    for line in lines:
        var fields = line.split(":")
        var name = fields[0]
        counts[name] = counts.get(name, 0) + int(fields[1])
    var names = counts.keys()
    names.sort()
    var rows = PackedStringArray()
    for name in names:
        if counts[name] > 0:
            rows.append(name + "=" + str(counts[name]))
    return "empty" if rows.is_empty() else ",".join(rows)
func _init():
    var lines = []
    while true:
        var line = OS.read_string_from_stdin().strip_edges()
        if line == "":
            break
        lines.append(line)
    print(inventory(lines))
    quit()

编辑 app.luau、inventory.luau。可见且已锁定的 main.luau 会从标准输入读取内容并存入一系列行,调用 app.run(lines),然后打印其返回值,末尾带一个换行符。不要打印诊断信息,也不要更改模块名称。空输入会生成一个空序列。所有数值输入都足够小,不会溢出。

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

参考程序使用一个精简的 SceneTree 框架来读取标准输入。对于这个格式正确且不含空白行的输入范围,空行检查会在到达文件末尾时终止。请移植业务模型和输出约定;Luau 驱动程序会提供输入行,无需引擎生命周期。

亲手试试

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

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

自己练习: Luau 在线编译器