インベントリをLuauに移植する
Coddyの「Luau開発者のためのLua」コースのレッスン 28/29。
チャレンジ
中級参照用の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)を呼び出し、返された値を最後に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。入力が空の場合、一連の行は空になります。すべての数値入力はオーバーフローしない範囲です。
公開APIの確認: inventory.aggregate(lines)は、符号付き差分の合計を保持した新しいテーブルを返し、合計がゼロの項目も残します。入力が空の場合は空のテーブルを返します。書式設定とフィルタリングはappで行います。ロック済みのドライバーはapp.runを呼び出す前にこの動作を確認します。これらの確認は成功時には何も出力しません。
完全なLuauの参照コードは、サンプルのlinesテーブルで実行されます。別の入力を試すには、最初の行を置き換えてください。対象のドライバーは、同じデータを標準入力から渡します。必要なモジュールAPIを維持しながら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))
Luau開発者のためのLuaのすべてのレッスン
自分で練習してみよう: Luaオンラインコンパイラ