Conditionals
A conditional determines whether or not certain blocks of code will run. A conditional checks the value of an expression, called the condition. If the condition is false
, then the code block within the conditional will be skipped. Otherwise, the code block will be run.
Conditionals are used to control the flow of the execution of code within a program.
if
Conditionals
A basic if
conditional in Luau is given as follows:
if <condition> then
<code block>
end
Examples of basic if
conditionals
if true then --code block ranprint("code block ran")endif false then --no outputprint("code block ran")endif "chicken" then --code block ranprint("code block ran")end
else
and elseif
To augment the basic if
conditional, elseif
can be used to check additional conditions if the first condition is false
. Also, the else
keyword can be used as a catchall to run a code block if all previous conditions were false
.
if <condition 1> then
<code block 1>
elseif <condition 2> then
<code block 2>
else
<code block 3>
end
In the code above, condition 1
is checked first. condition 2
is checked only if condition 1
is false
. If the first two conditions are both false
, then code block 3
will be executed.
else
and elseif
examples
The following examples illustrate conditionals that use else
and elseif
.
if "tony" == "paulie" then --madone!print("ooh!")elseif "silvio" == "junior" thenprint("dooh!")elseprint("madone!")endif 3 >= 4 then --dooh!print("ooh!")elseif 23 thenprint("dooh!")elseprint("madone!")endif "AJ" == "AJ" and 3 < 10 then --ooh!print("ooh!")elseprint("dooh!")end
All contributors
- noahpgordon38 total contributions
- THE-Spellchecker154 total contributions
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.