条件语句 #

一、if 语句基础 #

1.1 基本 if 语句 #

lua
-- 基本语法
if condition then
    -- 条件为真时执行
end

-- 示例
local score = 85

if score >= 60 then
    print("及格")
end

1.2 if-else 语句 #

lua
-- 基本语法
if condition then
    -- 条件为真时执行
else
    -- 条件为假时执行
end

-- 示例
local score = 55

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

1.3 if-elseif-else 语句 #

lua
-- 基本语法
if condition1 then
    -- 条件1为真时执行
elseif condition2 then
    -- 条件2为真时执行
else
    -- 所有条件都不满足时执行
end

-- 示例:成绩等级
local score = 85

if score >= 90 then
    print("优秀")
elseif score >= 80 then
    print("良好")
elseif score >= 70 then
    print("中等")
elseif score >= 60 then
    print("及格")
else
    print("不及格")
end

二、条件表达式 #

2.1 真值与假值 #

lua
-- 只有 false 和 nil 是假值
-- 其他所有值都是真值

-- 假值
if false then print("不会执行") end
if nil then print("不会执行") end

-- 真值
if true then print("执行") end
if 0 then print("执行") end        -- 0 是真值
if "" then print("执行") end       -- 空字符串是真值
if {} then print("执行") end       -- 空表是真值

2.2 比较运算符 #

lua
local a, b = 10, 20

-- 相等
if a == b then print("相等") end

-- 不相等
if a ~= b then print("不相等") end

-- 大于
if a > b then print("a 大于 b") end

-- 小于
if a < b then print("a 小于 b") end

-- 大于等于
if a >= b then print("a 大于等于 b") end

-- 小于等于
if a <= b then print("a 小于等于 b") end

2.3 逻辑运算符 #

lua
local a, b = true, false

-- and:与运算
if a and b then
    print("两者都为真")
end

-- or:或运算
if a or b then
    print("至少一个为真")
end

-- not:非运算
if not b then
    print("b 为假")
end

-- 组合使用
local age = 25
local has_license = true

if age >= 18 and has_license then
    print("可以驾驶")
end

三、嵌套条件 #

3.1 嵌套 if 语句 #

lua
local score = 85
local attendance = 90

if score >= 60 then
    print("成绩及格")
    if attendance >= 80 then
        print("出勤率良好")
    else
        print("出勤率不足")
    end
else
    print("成绩不及格")
end

3.2 避免深层嵌套 #

lua
-- 不推荐:深层嵌套
local function process1(user)
    if user then
        if user.active then
            if user.role == "admin" then
                return "管理员"
            else
                return "普通用户"
            end
        else
            return "用户未激活"
        end
    else
        return "用户不存在"
    end
end

-- 推荐:提前返回
local function process2(user)
    if not user then
        return "用户不存在"
    end
    
    if not user.active then
        return "用户未激活"
    end
    
    if user.role == "admin" then
        return "管理员"
    end
    
    return "普通用户"
end

四、条件表达式技巧 #

4.1 三元运算模拟 #

lua
-- Lua 没有三元运算符,但可以用 and/or 模拟
local score = 75
local result = score >= 60 and "及格" or "不及格"
print(result)  -- 及格

-- 注意:如果 "真值" 为假,结果会错误
local a = true
local b = false
local c = "default"
local result = a and b or c  -- 得到 "default",但期望是 b

-- 更安全的方式
local function if_else(condition, true_val, false_val)
    if condition then
        return true_val
    else
        return false_val
    end
end

local result = if_else(score >= 60, "及格", "不及格")

4.2 默认值 #

lua
-- 使用 or 提供默认值
local function greet(name)
    name = name or "World"
    print("Hello, " .. name)
end

greet()        -- Hello, World
greet("Lua")   -- Hello, Lua

-- 链式默认值
local function get_config(user_config, default_config, system_config)
    return user_config or default_config or system_config or {}
end

4.3 范围检查 #

lua
-- 检查数值是否在范围内
local function in_range(value, min, max)
    return value >= min and value <= max
end

if in_range(age, 18, 65) then
    print("在工作年龄范围内")
end

-- 使用数学函数
local function clamp(value, min, max)
    return math.max(min, math.min(max, value))
end

五、模式匹配条件 #

5.1 字符串匹配 #

lua
local input = "hello.lua"

-- 检查后缀
if string.match(input, "%.lua$") then
    print("是 Lua 文件")
end

-- 检查是否包含数字
if string.match(input, "%d") then
    print("包含数字")
end

-- 检查邮箱格式
local function is_email(s)
    return string.match(s, "^[%w%.%-]+@[%w%.%-]+%.[%a]+$") ~= nil
end

5.2 类型检查 #

lua
local function process(value)
    local t = type(value)
    
    if t == "nil" then
        print("空值")
    elseif t == "number" then
        print("数字:" .. value)
    elseif t == "string" then
        print("字符串:" .. value)
    elseif t == "table" then
        print("表")
    elseif t == "function" then
        print("函数")
    else
        print("其他类型:" .. t)
    end
end

六、实用示例 #

6.1 用户认证 #

lua
local function authenticate(user, password)
    if not user then
        return false, "用户不存在"
    end
    
    if not user.active then
        return false, "用户已禁用"
    end
    
    if user.password ~= password then
        return false, "密码错误"
    end
    
    return true, "认证成功"
end

local success, message = authenticate(current_user, input_password)
if success then
    print("登录成功")
else
    print("登录失败:" .. message)
end

6.2 数据验证 #

lua
local function validate_user(user)
    if not user then
        return false, "用户数据为空"
    end
    
    if not user.name or #user.name < 2 then
        return false, "姓名长度不足"
    end
    
    if not user.email or not string.match(user.email, "^[%w%.%-]+@") then
        return false, "邮箱格式错误"
    end
    
    if not user.age or user.age < 0 or user.age > 150 then
        return false, "年龄无效"
    end
    
    return true, "验证通过"
end

6.3 游戏状态判断 #

lua
local function check_game_state(player)
    if player.health <= 0 then
        return "game_over"
    end
    
    if player.score >= 1000 then
        return "win"
    end
    
    if player.lives <= 0 then
        return "game_over"
    end
    
    if player.time <= 0 then
        return "timeout"
    end
    
    return "playing"
end

local state = check_game_state(current_player)
if state == "game_over" then
    show_game_over_screen()
elseif state == "win" then
    show_victory_screen()
end

6.4 配置解析 #

lua
local function parse_config(config)
    local result = {}
    
    -- 设置默认值
    result.host = config.host or "localhost"
    result.port = config.port or 8080
    result.timeout = config.timeout or 30
    
    -- 验证端口范围
    if result.port < 1 or result.port > 65535 then
        result.port = 8080
    end
    
    -- 验证超时时间
    if result.timeout < 0 then
        result.timeout = 30
    end
    
    return result
end

七、性能优化 #

7.1 条件顺序 #

lua
-- 将最可能为真的条件放在前面
local function get_grade(score)
    -- 假设大部分学生成绩在 60-80 之间
    if score >= 60 and score < 80 then
        return "中等"
    elseif score >= 80 and score < 90 then
        return "良好"
    elseif score >= 90 then
        return "优秀"
    else
        return "不及格"
    end
end

7.2 避免重复计算 #

lua
-- 不推荐:重复计算
if calculate_value() > 100 then
    process(calculate_value())
end

-- 推荐:缓存结果
local value = calculate_value()
if value > 100 then
    process(value)
end

八、常见错误 #

8.1 赋值与比较混淆 #

lua
-- 错误:使用 = 而不是 ==
-- if a = 10 then end  -- 语法错误

-- 正确:使用 ==
if a == 10 then end

8.2 浮点数比较 #

lua
-- 错误:直接比较浮点数
local a = 0.1 + 0.2
if a == 0.3 then  -- false!
    print("相等")
end

-- 正确:使用容差比较
local function almost_equal(x, y, epsilon)
    epsilon = epsilon or 1e-10
    return math.abs(x - y) < epsilon
end

if almost_equal(a, 0.3) then
    print("相等")
end

8.3 nil 检查 #

lua
-- 错误:访问 nil 的字段
local user = nil
-- if user.name == "admin" then end  -- 错误!

-- 正确:先检查 nil
if user and user.name == "admin" then
    print("管理员")
end

九、总结 #

本章介绍了 Lua 的条件语句:

  1. if 语句:基本条件判断
  2. if-else 语句:二选一分支
  3. if-elseif-else 语句:多分支判断
  4. 条件表达式:比较运算符和逻辑运算符
  5. 嵌套条件:合理使用,避免深层嵌套
  6. 实用技巧:三元运算模拟、默认值、范围检查

掌握条件语句是编写逻辑控制代码的基础。下一章,我们将学习循环语句。

最后更新:2026-03-27