学文网

Lua中if ... else语句的详解用法

时间:2023-08-15 10:32:34 文/李盛老师 句子学文网www.xuewenya.com

Lua中if ... else语句的详解用法

  if 语句后面可以跟一个可选的else语句,当布尔表达式为假该语句执行。

  语法

  在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和非零值的任意组合作为true,以及它是否是布尔假或零,则假定为false值。但应当注意的是,在Lua零值被视为true。

  例如:

  代码如下:

  --[ 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 可以有零或一个 else ,但必须在elseif之前。

  if 之后可以有零到很多else if在else之前。

  一旦一个else if成功,其它的elseif将不会被测试。

  语法

  if...else if...else...else语句在Lua编程语言的语法是:

  代码如下:

  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

推荐文章

四川高考排名125230左右排位文科可以上哪些大学,具体能上什么大学2024-06-04 12:57:05

西南交通大学希望学院和北京农学院哪个好 附对比和区别排名2024-06-04 12:53:13

广东高考排名249380左右排位物理可以上哪些大学,具体能上什么大学2024-06-04 12:50:07

黑龙江高考排名20460左右排位理科可以上哪些大学,具体能上什么大学2024-06-04 12:46:59

湖北高考排名115550左右排位物理可以上哪些大学,具体能上什么大学2024-06-04 12:43:10

长春师范大学和广州大学哪个好 附对比和区别排名2024-06-04 12:39:13

38妇女节的祝福妈妈2023-08-14 22:08:10

分手时感人的语句2023-08-16 07:09:25

邓文原传阅读答案2023-08-18 18:19:39

人造太阳阅读答案2023-08-10 09:56:17

分手时感人的语句2023-08-16 07:09:25

鼓励别人经典语句2023-08-19 16:13:55

描写景物的语句2023-08-13 04:13:52

思考人生的古风句子2023-08-22 21:50:28

情侣的句子古风版2023-08-13 09:14:34

汇总唯美伤感的古风句子2023-08-27 15:02:30

最新文章

精华文章

热门排序