ポーションの販売
CoddyのLuaジャーニー「基礎」セクションの一部 — レッスン 82/90。
チャレンジ
簡単販売取引システムを実装して、ポーションショップのプロジェクトを完成させましょう。検索機能をベースにして、ポーションの販売を処理し、stockの数量を減らして取引の確認を出力するシステムを作成します。
以下の入力が提供されます:
- 販売するポーションの名前を含む文字列
数値forループを使用してinventoryテーブルを反復処理し、指定されたポーションを検索します。等価演算子 == を使用して一致するポーションを見つけたら、その stock の値を 1 減らして販売をシミュレートします。
在庫を更新した後、ポーションの名前と新しい在庫数を次の形式で表示する確認メッセージを出力します:
Sold 1 [potion name]
Remaining stock: [new stock count]文字列連結を使用して、説明テキストとポーションの名前、更新された在庫数量を組み合わせます。販売処理を完了したら、break ステートメントを使用してループを終了します。
自分で試してみよう
-- Inventory table with potion data
inventory = {
{name = "Health Potion", price = 15, stock = 8},
{name = "Mana Potion", price = 12, stock = 5},
{name = "Strength Potion", price = 25, stock = 3},
{name = "Speed Potion", price = 18, stock = 2}
}
-- Read the potion name to search for
search_name = io.read()
-- Use a numeric for loop to search through the inventory
for i = 1, #inventory do
if inventory[i].name == search_name then
print("Found: " .. inventory[i].name)
print("Price: " .. inventory[i].price .. " gold")
print("Stock: " .. inventory[i].stock .. " units")
break
end
end