在庫を表示する
CoddyのLuaジャーニー「基礎」セクションの一部。レッスン 79/90。
チャレンジ
簡単ポーションが1つ入ったインベントリをもとに、ショップで購入可能なすべてのポーションを表示するシステムを作成しましょう。まず、次のプロパティを持つ辞書形式のテーブル manaPotion を作成して、インベントリに2つ目のポーションを追加します。
- 値が
"Mana Potion"のname - 値が
12のprice - 値が
5のstock
table.insert() を使って、この manaPotion を inventory テーブルに追加します。
次に、数値型の for ループを使って inventory テーブルを反復処理する表示システムを作成します。インベントリ内の各ポーションについて、ポーションの名前と価格を次の形式で出力します。"[name]: [price] gold"。文字列連結を使って、ポーションの name と price を説明文と結合します。
リスト形式のテーブルのすべての要素を確認するには、1 からその長さ(#)までループし、各要素のフィールドをドット記法で読み取ります。たとえば、別のテーブルの場合は次のようになります。
heroes = {
{name = "Ana", level = 3},
{name = "Ben", level = 7}
}
for i = 1, #heroes do
print(heroes[i].name)
end前のステップの print(#inventory) の行を削除して、ポーションの一覧だけが出力されるようにします。
自分で試してみよう
-- Create empty inventory table
local inventory = {}
-- Create health potion table
local healthPotion = {
name = "Health Potion",
price = 15,
stock = 8
}
-- Add health potion to inventory
table.insert(inventory, healthPotion)
-- Print the length of inventory
print(#inventory)基礎のすべてのレッスン
自分で練習してみよう: Luaオンラインコンパイラ