Menu
CoddyTech

在庫を表示する

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

challenge icon

チャレンジ

簡単

ポーションが1つ入ったインベントリを拡張して、お店で利用可能なすべてのポーションを表示するシステムを作成しましょう。まず、次のプロパティを持つmanaPotionという辞書形式のテーブルを作成して、インベントリに2つ目のポーションを追加します。

  • nameの値は"Mana Potion"
  • priceの値は12
  • stockの値は5

table.insert()を使って、このmanaPotionをinventoryテーブルに追加します。

次に、数値型のforループを使ってinventoryテーブルを順に処理する表示システムを作成します。インベントリ内の各ポーションについて、ポーションの名前と価格を"[name]: [price] gold"の形式で出力します。文字列連結を使って、ポーションのnameとpriceを説明文と結合します。

前のステップの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オンラインコンパイラ