特定のポーションの検索
CoddyのLuaジャーニー「Fundamentals」セクションの一部 — レッスン 81/90。
チャレンジ
簡単在庫価値計算システムを基に、ショップの在庫にある特定のポーションを検索して詳細情報を表示する機能を実装しましょう。
以下の入力が与えられます:
- 検索するポーションの名前を含む文字列
数値 for ループを使用して inventory テーブルを反復処理します。各ポーションについて、等価演算子 == を使用してポーションの name が検索語と一致するかどうかをチェックしてください。
一致するポーションが見つかったら、そのすべての詳細を次の形式で出力してください:
Found: [name]
Price: [price] gold
Stock: [stock] units文字列結合を使用して、説明テキストと各ポーションのプロパティを組み合わせます。ポーションの詳細を見つけて表示したら、目的のものが見つかったので break 文を使用してループを抜けてください。
自分で試してみよう
-- Inventory table with potion data
local 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}
}
-- Initialize total value variable
local totalValue = 0
-- Calculate total inventory value using numeric for loop
for i = 1, #inventory do
local itemValue = inventory[i].price * inventory[i].stock
totalValue = totalValue + itemValue
end
-- Print the total inventory value
print("Total inventory value: " .. totalValue .. " gold")