GDScriptのインベントリを移植する
Coddyの「GDScript開発者のためのLua」コースのレッスン 47/48。
チャレンジ
中級参照用の GDScript プログラムを Lua モジュールに移植してください。各入力行は、小文字の ASCII 名、コロン、符号付き整数の差分で構成されます。名前ごとに集計し、最終合計が正のものだけを残し、名前を昇順に並べて、カンマで結合した name=total のエントリーを返します。残るものがなければ empty を返します。inventory.lua に inventory.aggregate(lines) を実装してください。結果の書式設定は app が行います。入力行はすべて正しい形式です。
app.lua と inventory.lua を編集してください。表示されているロック済みの main.lua は、標準入力を一連の行として読み取り、app.run(lines) を呼び出し、返された値を最後に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。空の入力は空のシーケンスになります。数値入力はすべてオーバーフローしない範囲です。
公開 API の確認: inventory.aggregate(lines) は、符号付き差分を合計した新しいテーブルを返し、合計がゼロのものも保持します。空の入力では空のテーブルが返されます。書式設定とフィルタリングは app で行います。ロック済みのドライバーは app.run を呼び出す前にこの動作を確認します。これらの確認は成功しても何も出力しません。
GDScript 4 の参照コード
ヘッドレススクリプトとして実行します。エントリーポイントは標準入力を読み取り、結果を1つ出力して終了します。提供された Lua モジュールに移植する際は、ドメインの動作を維持してください。
extends SceneTree
# Input lines are lowercase names followed by a colon and a signed integer.
# A blank read marks EOF because the input contract excludes blank lines.
func _init() -> void:
var counts: Dictionary = {}
while true:
var line := OS.read_string_from_stdin()
if line.is_empty():
break
var parts := line.split(":")
var item := parts[0]
counts[item] = counts.get(item, 0) + int(parts[1])
var names: Array = counts.keys()
names.sort()
var rows: PackedStringArray = []
for item in names:
if counts[item] > 0:
rows.append("%s=%d" % [item, counts[item]])
print(",".join(rows) if not rows.is_empty() else "empty")
quit()自分で試してみよう
-- 公開 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開発者のためのLuaのすべてのレッスン
自分で練習してみよう: Luaオンラインコンパイラ