Menu
Coddy logo textTech

ポーションの販売

CoddyのLuaジャーニー「Fundamentals」セクションの一部 — レッスン 82/90。

challenge icon

チャレンジ

簡単

販売トランザクションシステムを実装して、ポーションショップのプロジェクトを完成させましょう。検索機能を基にして、在庫数を減らし、取引の確認を表示することでポーションの販売を処理するシステムを作成します。

次の入力が提供されます:

  • 販売するポーションの名前を含む文字列

数値の 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

Fundamentalsのすべてのレッスン