在庫の合計額を計算する
CoddyのLuaジャーニー「基礎」セクションの一部。レッスン 80/90。
チャレンジ
簡単次のインベントリを使ってください(現在のものを置き換えてもかまいません):
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オンラインコンパイラ