Appearance
流程控制
流程控制是编程中用于控制程序执行流程的结构。Lua 提供了多种流程控制语句,本章节将介绍这些语句的使用方法。
if 语句
if 语句用于根据条件执行不同的代码块:
lua
local score = 85
if score >= 90 then
print("优秀")
elseif score >= 60 then
print("及格")
else
print("不及格")
end输出:
及格if-else 语句
if-else 语句用于在条件为真时执行一个代码块,否则执行另一个代码块:
lua
local age = 18
if age >= 18 then
print("成年人")
else
print("未成年人")
end输出:
成年人if-elseif-else 语句
if-elseif-else 语句用于处理多个条件:
lua
local grade = "B"
if grade == "A" then
print("优秀")
elseif grade == "B" then
print("良好")
elseif grade == "C" then
print("及格")
else
print("不及格")
end输出:
良好嵌套 if 语句
if 语句可以嵌套使用:
lua
local score = 85
local attendance = 90
if score >= 60 then
if attendance >= 80 then
print("及格")
else
print("考勤不足,不及格")
end
else
print("不及格")
end输出:
及格逻辑运算符与条件
可以使用逻辑运算符组合多个条件:
lua
local age = 25
local hasJob = true
if age >= 18 and hasJob then
print("成年人且有工作")
end
local score = 50
local hasBonus = true
if score >= 60 or hasBonus then
print("及格或有 bonus")
end
local isStudent = false
if not isStudent then
print("不是学生")
end输出:
成年人且有工作
及格或有 bonus
不是学生短路求值
Lua 中的逻辑运算符支持短路求值:
lua
-- 当第一个条件为假时,不会执行第二个条件
local a = nil
local b = 10
if a and b then
print("a 和 b 都为真")
end
-- 当第一个条件为真时,不会执行第二个条件
local c = true
local d = nil
if c or d then
print("c 或 d 为真")
end输出:
c 或 d 为真三元运算符
Lua 没有内置的三元运算符,但可以使用 and 和 or 模拟:
lua
local score = 85
local result = score >= 60 and "及格" or "不及格"
print(result)输出:
及格流程控制的应用
示例 1:判断奇偶性
lua
local num = 10
if num % 2 == 0 then
print("偶数")
else
print("奇数")
end输出:
偶数示例 2:判断闰年
lua
local year = 2020
if (year % 4 == 0 and year % 100 ~= 0) or year % 400 == 0 then
print("闰年")
else
print("平年")
end输出:
闰年示例 3:成绩等级判断
lua
local score = 75
if score >= 90 then
print("A")
elseif score >= 80 then
print("B")
elseif score >= 70 then
print("C")
elseif score >= 60 then
print("D")
else
print("F")
end输出:
C小结
本章节介绍了 Lua 中的流程控制语句,包括 if 语句、if-else 语句、if-elseif-else 语句、嵌套 if 语句,以及逻辑运算符与条件的使用。掌握这些流程控制语句,对于编写 Lua 程序非常重要。