On this page

Lua 条件控制

Lua 条件控制结构

Lua 提供了灵活的条件控制结构,主要包括 if 语句和 switch 模拟(Lua 5.3+)。以下是详细说明:

1. if 语句

基本形式

if 条件 then
    -- 条件为真时执行的代码
end

示例:

local age = 18
if age >= 18 then
    print("你已成年")
end

if-else 结构

if 条件 then
    -- 条件为真时执行
else
    -- 条件为假时执行
end

示例:

local score = 85
if score >= 60 then
    print("及格")
else
    print("不及格")
end

if-elseif-else 多分支结构

if 条件1 then
    -- 条件1为真时执行
elseif 条件2 then
    -- 条件2为真时执行
elseif 条件3 then
    -- 条件3为真时执行
else
    -- 以上条件都不满足时执行
end

示例:

local grade = "B"
if grade == "A" then
    print("优秀")
elseif grade == "B" then
    print("良好")
elseif grade == "C" then
    print("及格")
else
    print("不及格")
end

2. Lua 中的真与假

Lua 条件判断的特殊规则:

  • falsenil 视为假
  • 其他所有值(包括0、空字符串等)都视为真

示例:

if 0 then print("0为真") end          -- 会执行
if "" then print("空字符串为真") end  -- 会执行
if nil then else print("nil为假") end  -- 会打印"nil为假"

3. 逻辑运算符在条件中的使用

-- and 运算符
if a > 0 and b > 0 then
    print("a和b都大于0")
end

-- or 运算符
if a > 0 or b > 0 then
    print("a或b大于0")
end

-- not 运算符
if not isFinished then
    print("未完成")
end

4. 三目运算模拟

Lua 没有专门的三目运算符,但可以用 and-or 模拟:

local result = (条件) and 值1 or 值2

示例:

local age = 20
local status = (age >= 18) and "成年" or "未成年"
print(status)  -- 输出"成年"

注意:值1不能为false或nil,否则会错误地返回值2

5. switch-case 模拟(Lua 5.3+)

Lua 没有 switch 语句,但有几种模拟方式:

方式1:使用 if-elseif

local value = 2
if value == 1 then
    print("一")
elseif value == 2 then
    print("二")
elseif value == 3 then
    print("三")
else
    print("其他")
end

方式2:使用表映射

local actions = {
    [1] = function() print("执行操作1") end,
    [2] = function() print("执行操作2") end,
    [3] = function() print("执行操作3") end
}

local case = 2
local action = actions[case]
if action then
    action()
else
    print("默认操作")
end

6. 最佳实践建议

  1. 简单的条件判断优先使用 if
  2. 多分支条件超过3个时,考虑使用表映射方式
  3. 复杂的条件表达式可以拆分为多个局部变量
    local isAdult = age >= 18
    local hasTicket = ticket ~= nil
    if isAdult and hasTicket then
        -- ...
    end
    
  4. 避免过深的嵌套条件(超过3层应考虑重构)

Lua的条件控制结构虽然简单,但配合其灵活的布尔值判断规则,可以处理各种复杂的条件逻辑。