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)を呼び出し、その返り値を最後の改行1つとともに出力します。診断情報を出力したり、モジュール名を変更したりしないでください。空の入力は空のシーケンスを生成します。すべての数値入力はオーバーフローを回避できる十分小さな値です。

パブリック 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オンラインコンパイラ