Lua-if-else-statement-in-lua
提供:Dev Guides
Lua-if … elseステートメント
*if* ステートメントの後にオプションの *else* ステートメントを続けることができます。これは、ブール式がfalseの場合に実行されます。
構文
Luaプログラミング言語の if … else ステートメントの構文は-
if(boolean_expression)
then
--[ statement(s) will execute if the boolean expression is true --]
else
--[ statement(s) will execute if the boolean expression is false --]
end
ブール式が true と評価されると、コードの* ifブロック*が実行され、そうでない場合はコードの* elseブロック*が実行されます。
Luaプログラミング言語は、ブール値 true および non-nil 値の任意の組み合わせを true と見なし、ブール値 false または nil の場合、 false 値と見なされます。 Luaでは、ゼロが真と見なされることに注意してください。
流れ図
例
--[ local variable definition --]
a = 100;
--[ check the boolean condition --]
if( a < 20 )
then
--[ if condition is true then print the following --]
print("a is less than 20" )
else
--[ if condition is false then print the following --]
print("a is not less than 20" )
end
print("value of a is :", a)
上記のコードをビルドして実行すると、次の結果が生成されます。
a is not less than 20
value of a is : 100
if … else if … elseステートメント
*if* ステートメントの後にオプションの *else if ... else* ステートメントを続けることができます。これは、単一のif ... else ifステートメントを使用してさまざまな条件をテストするのに非常に便利です。
if、else if、elseステートメントを使用している間、留意すべき点がいくつかあります-
- _if_にはゼロまたは1つのelseを含めることができ、else ifの後に来る必要があります。
- _if_は、他のifのゼロから多数まであり、elseの前に来る必要があります。
- _else if_が成功すると、残りのelse ifまたはelseはテストされません。
構文
Luaプログラミング言語の if … else if … else ステートメントの構文は-
if(boolean_expression 1)
then
--[ Executes when the boolean expression 1 is true --]
else if( boolean_expression 2)
--[ Executes when the boolean expression 2 is true --]
else if( boolean_expression 3)
--[ Executes when the boolean expression 3 is true --]
else
--[ executes when the none of the above condition is true --]
end
例
--[ local variable definition --]
a = 100
--[ check the boolean condition --]
if( a == 10 )
then
--[ if condition is true then print the following --]
print("Value of a is 10" )
elseif( a == 20 )
then
--[ if else if condition is true --]
print("Value of a is 20" )
elseif( a == 30 )
then
--[ if else if condition is true --]
print("Value of a is 30" )
else
--[ if none of the conditions is true --]
print("None of the values is matching" )
end
print("Exact value of a is: ", a )
上記のコードをビルドして実行すると、次の結果が生成されます。
None of the values is matching
Exact value of a is: 100