プログラミング入門
Luauのif文・条件分岐をマスターしよう
「スコアが100以上なら勝ち」「体力が0なら死亡」——ゲームはこんな「条件判断」だらけだよ。 if文を使いこなせれば、思い通りのゲームロジックが書けるようになるんだ!
この記事でわかること
- if文の基本構造
- elseif と else の使い方
- 比較演算子の種類
- andとorで複数条件を組み合わせる
- ゲームでの実践例
if文の分岐フロー
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)