Menu
CoddyTech

在庫の合計金額を計算する

CoddyのLuaジャーニー「基礎」セクションの一部。レッスン 80/90。

challenge icon

チャレンジ

簡単

次の在庫を使ってください(現在の在庫を上書きしてもかまいません):

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}
}


目標は、在庫にあるすべてのポーションの合計金額をゴールドで求めることです。

手順は次のとおりです。

1. totalValueという変数を作成し、0を設定します。これによって、各ポーションを確認しながら合計を記録できます。

2. 数値型のforループを使って、inventoryテーブルの各項目を確認します。各ポーションについて、priceにstockを掛けて、そのポーションの価値を求めます。その数値をtotalValueに加算します。

3. ループの後、次のように結果を出力します。

Total inventory value: 291 gold

文字列連結(..)を使って、テキストとtotalValueの値を結合します。

前のステップの表示用ループを削除してください。このステップでは合計の行だけを出力します。

自分で試してみよう

-- Create the initial inventory with health potion
inventory = {
    {name = "Health Potion", price = 15, stock = 8}
}

-- Create mana potion
manaPotion = {name = "Mana Potion", price = 12, stock = 5}

-- Add mana potion to inventory
table.insert(inventory, manaPotion)

-- Display all potions in inventory
for i = 1, #inventory do
    print(inventory[i].name .. ": " .. inventory[i].price .. " gold")
end

基礎のすべてのレッスン

自分で練習してみよう: Luaオンラインコンパイラ