Back to Unit 6

Lesson 1: if "condition" then

Unit 6: Control Structures

Lesson Content
Coding Challenge

If Statements in Lua

In Lua, the if statement allows you to execute code conditionally. The basic syntax is:

if condition then
    -- code to execute if condition is true
end

The condition is evaluated, and if it's true (any value other than false or nil), the code inside the if block is executed.

Examples

Basic if statement:

local playerHealth = 50

if playerHealth < 100 then
    print("Player is not at full health!")
end

Using comparison operators:

  • Equal to: ==
  • Not equal to: ~=
  • Greater than: >
  • Less than: <
  • Greater than or equal to: >=
  • Less than or equal to: <=
local playerLevel = 10

if playerLevel >= 10 then
    print("Player can use advanced weapons!")
end

In Roblox, if statements are commonly used to check player conditions, part collisions, and game states.

Health Status Challenge

Create a function that takes a player's health value and returns a status message based on the health value.

Instructions:

  • Create a function called 'getHealthStatus' that takes a number parameter 'health'
  • If health is 100 or greater, return 'Full Health'
  • If health is between 50 and 99, return 'Moderate Health'
  • If health is between 25 and 49, return 'Low Health'
  • If health is below 25, return 'Critical Health'

Code:

Output:

Run your code to see output