メインコンテンツへスキップ
RobuCraft
プログラミング入門

Luauのif文・条件分岐をマスターしよう

「スコアが100以上なら勝ち」「体力が0なら死亡」——ゲームはこんな「条件判断」だらけだよ。 if文を使いこなせれば、思い通りのゲームロジックが書けるようになるんだ!

この記事でわかること

  1. if文の基本構造
  2. elseif と else の使い方
  3. 比較演算子の種類
  4. andとorで複数条件を組み合わせる
  5. ゲームでの実践例

if文の分岐フロー

条件をチェックtruethen処理実行falseelse処理実行end(終了)

if文の基本構造

Luauのif文は「if 条件 then ... end」という形で書くよ。 日本語で言うと「もし〜なら、〜する」だね。

local score = 80

if score >= 100 then
    print("完璧!")
elseif score >= 70 then
    print("合格!")
elseif score >= 50 then
    print("もう少し!")
else
    print("もっと練習しよう")
end

ポイント: 必ず「end」で閉じること。end を忘れると「expected 'end'」エラーが出るよ。

比較演算子の種類

記号意味
==等しいscore == 100
~=等しくないscore ~= 0
>より大きいscore > 50
<より小さいscore < 10
>=以上score >= 70
<=以下score <= 30

andとorで複数条件を組み合わせる

local level = 5
local hasKey = true

-- and: 両方の条件が true のとき
if level >= 3 and hasKey then
    print("ボスエリアに入れる!")
end

-- or: どちらかの条件が true のとき
if level >= 10 or hasKey then
    print("特別な部屋に入れる")
end

ゲームでの実践例: HPが0になったらリスポーン

local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        local humanoid = character:WaitForChild("Humanoid")

        humanoid.HealthChanged:Connect(function(health)
            if health <= 0 then
                print(player.Name .. "がやられた!")
                task.wait(3)
                player:LoadCharacter()  -- リスポーン
            end
        end)
    end)
end)

Luauを実際に書いて覚えよう

RobuCraftではif文を含むLuauの基礎を、AIメンターと一緒に学べるよ。 わからないところはロブ先生に何でも聞いてみよう!

RobuCraftで無料で始める