Skip to content

Lua运算符

概述

Lua提供了丰富的运算符,包括算术运算符、关系运算符、逻辑运算符等。理解这些运算符是编写Lua程序的基础。

1. 算术运算符

用于执行数学运算。

运算符描述示例结果
+加法10 + 313
-减法10 - 37
*乘法10 * 330
/除法10 / 33.3333333333333
//整数除法10 // 33
%取模10 % 31
^幂运算2 ^ 38
-负号(一元)-5-5

示例代码

lua
local a = 10
local b = 3

print("加法:", a + b)    -- 13
print("减法:", a - b)    -- 7
print("乘法:", a * b)    -- 30
print("除法:", a / b)    -- 3.3333333333333
print("整数除法:", a // b)  -- 3
print("取模:", a % b)    -- 1
print("幂运算:", a ^ b)   -- 1000

-- 负号
local c = -a
print("负数:", c)        -- -10

运算优先级

lua
-- 幂运算优先级最高
print(2 + 3 ^ 2)    -- 11 (等同于 2 + (3^2))

-- 乘除优先于加减
print(2 + 3 * 4)    -- 14 (等同于 2 + (3*4))

-- 使用括号改变优先级
print((2 + 3) * 4)  -- 20

2. 关系运算符

用于比较两个值,返回布尔值。

运算符描述示例结果
==等于5 == 5true
~=不等于5 ~= 3true
<小于3 < 5true
>大于5 > 3true
<=小于等于3 <= 5true
>=大于等于5 >= 5true

示例代码

lua
local x = 10
local y = 20

print(x == y)   -- false
print(x ~= y)   -- true
print(x < y)    -- true
print(x > y)    -- false
print(x <= y)   -- true
print(x >= y)   -- false

-- 字符串比较
local str1 = "abc"
local str2 = "def"
print(str1 < str2)   -- true (按字典序比较)

-- 不同类型比较
print(10 == "10")    -- false (类型不同)
print(nil == false)  -- false (nil不等于false)

比较规则

lua
-- 数字比较
print(3.0 == 3)      -- true (数值相等)

-- 字符串比较(字典序)
print("apple" < "banana")  -- true
print("Apple" < "apple")   -- true (大写字母ASCII值小)

-- 表比较(引用比较)
local t1 = {1, 2, 3}
local t2 = {1, 2, 3}
local t3 = t1

print(t1 == t2)  -- false (不同的表对象)
print(t1 == t3)  -- true (相同的引用)

3. 逻辑运算符

用于逻辑运算,支持短路求值。

运算符描述示例结果
and逻辑与true and falsefalse
or逻辑或true or falsetrue
not逻辑非not truefalse

示例代码

lua
local a = true
local b = false

print(a and b)   -- false
print(a or b)    -- true
print(not a)     -- false
print(not b)     -- true

-- 短路求值
local x = 5
local y = 0

-- and:如果第一个为假,不会计算第二个
local result1 = (y ~= 0) and (x / y > 2)
print(result1)   -- false

-- or:如果第一个为真,不会计算第二个
local result2 = (x > 0) or (x / y > 2)
print(result2)   -- true

逻辑运算的特殊性

lua
-- 在Lua中,只有nil和false为假,其他都为真
print(0 and "zero")      -- "zero" (0为真)
print("" and "empty")    -- "empty" (空字符串为真)
print({} and "table")    -- "table" (空表为真)

-- and返回第一个假值或最后一个真值
print(1 and 2 and 3)     -- 3
print(1 and nil and 3)   -- nil

-- or返回第一个真值或最后一个假值
print(nil or false or 5) -- 5
print(nil or false)      -- false

实用模式

lua
-- 设置默认值
local function greet(name)
    name = name or "World"  -- 如果name为nil,使用"World"
    return "Hello, " .. name
end

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

-- 条件赋值
local config = {
    debug = true,
    port = nil
}

local port = config.port or 8080  -- 如果port为nil,使用8080
print(port)  -- 8080

-- 安全调用
local function safe_divide(a, b)
    return b ~= 0 and a / b or "除数不能为零"
end

print(safe_divide(10, 2))  -- 5
print(safe_divide(10, 0))  -- 除数不能为零

4. 字符串运算符

连接运算符 (..)

lua
local first = "Hello"
local second = "World"
local result = first .. " " .. second
print(result)  -- Hello World

-- 数字会自动转换为字符串
local num = 42
local str = "The answer is " .. num
print(str)  -- The answer is 42

-- 多个连接
local full_name = "John" .. " " .. "Doe"
print(full_name)  -- John Doe

长度运算符 (#)

lua
local str = "Hello, Lua!"
print(#str)  -- 12

local arr = {1, 2, 3, 4, 5}
print(#arr)  -- 5

-- 注意:对于有空洞的数组,结果可能不准确
local sparse = {1, 2, nil, 4, 5}
print(#sparse)  -- 结果不确定

5. 表运算符

长度运算符 (#)

lua
-- 对于序列(连续整数索引的表)
local sequence = {10, 20, 30, 40}
print(#sequence)  -- 4

-- 对于非序列表,结果不确定
local dict = {name = "Lua", version = 5.4}
print(#dict)  -- 0

-- 混合表
local mixed = {1, 2, 3, name = "test"}
print(#mixed)  -- 3 (只计算数组部分)

6. 运算符优先级

从高到低的优先级顺序:

  1. ^ (幂运算)
  2. not # - (一元运算符)
  3. * / // % (乘除运算)
  4. + - (加减运算)
  5. .. (字符串连接)
  6. < <= > >= ~= == (关系运算)
  7. and (逻辑与)
  8. or (逻辑或)

优先级示例

lua
-- 幂运算优先级最高
print(2 ^ 3 ^ 2)    -- 512 (等同于 2^(3^2))

-- 一元运算符
print(-2 ^ 2)       -- -4 (等同于 -(2^2))
print((-2) ^ 2)     -- 4

-- 算术运算
print(2 + 3 * 4)    -- 14 (等同于 2 + (3*4))

-- 字符串连接
print("a" .. "b" .. "c")  -- abc

-- 关系和逻辑运算
print(1 < 2 and 3 < 4)    -- true
print(1 < 2 or 3 > 4)     -- true

7. 特殊运算符用法

三元运算符模拟

lua
-- Lua没有三元运算符,但可以用and/or模拟
local function max(a, b)
    return a > b and a or b
end

print(max(10, 5))  -- 10
print(max(3, 8))   -- 8

-- 注意:当真值可能为false或nil时,这种方法不适用
local function safe_ternary(condition, true_val, false_val)
    if condition then
        return true_val
    else
        return false_val
    end
end

空值合并

lua
-- 类似于其他语言的 ?? 运算符
local function coalesce(...)
    local args = {...}
    for i = 1, #args do
        if args[i] ~= nil then
            return args[i]
        end
    end
    return nil
end

local result = coalesce(nil, nil, "default", "backup")
print(result)  -- default

链式比较

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

print(in_range(5, 1, 10))   -- true
print(in_range(15, 1, 10))  -- false

8. 实际应用示例

配置验证

lua
local function validate_config(config)
    -- 使用逻辑运算符进行验证
    local is_valid = config and
                    type(config.host) == "string" and
                    type(config.port) == "number" and
                    config.port > 0 and config.port < 65536
    
    return is_valid
end

local config1 = {host = "localhost", port = 8080}
local config2 = {host = "localhost", port = -1}

print(validate_config(config1))  -- true
print(validate_config(config2))  -- false

数学计算

lua
-- 计算圆的面积和周长
local function circle_properties(radius)
    local pi = math.pi
    local area = pi * radius ^ 2
    local circumference = 2 * pi * radius
    return area, circumference
end

local area, circumference = circle_properties(5)
print(string.format("面积: %.2f, 周长: %.2f", area, circumference))

字符串处理

lua
-- 构建SQL查询
local function build_query(table_name, conditions)
    local query = "SELECT * FROM " .. table_name
    
    if conditions and #conditions > 0 then
        query = query .. " WHERE " .. table.concat(conditions, " AND ")
    end
    
    return query
end

local conditions = {"age > 18", "status = 'active'"}
local sql = build_query("users", conditions)
print(sql)  -- SELECT * FROM users WHERE age > 18 AND status = 'active'

9. 常见陷阱和注意事项

浮点数比较

lua
-- 避免直接比较浮点数
local a = 0.1 + 0.2
local b = 0.3

print(a == b)  -- 可能为false

-- 使用epsilon比较
local function float_equal(a, b, epsilon)
    epsilon = epsilon or 1e-10
    return math.abs(a - b) < epsilon
end

print(float_equal(a, b))  -- true

字符串和数字比较

lua
-- 不同类型不会自动转换
print("10" == 10)    -- false
print("10" < 20)     -- 错误!不能比较字符串和数字

-- 需要显式转换
print(tonumber("10") == 10)  -- true

逻辑运算的短路特性

lua
local function expensive_operation()
    print("执行昂贵操作")
    return true
end

-- 利用短路特性避免不必要的计算
local condition = false
local result = condition and expensive_operation()
-- "执行昂贵操作"不会被打印

总结

Lua的运算符系统简洁而强大:

  1. 算术运算符支持基本数学运算,包括整数除法和幂运算
  2. 关系运算符用于值比较,注意类型敏感性
  3. 逻辑运算符支持短路求值,可用于实现条件赋值
  4. 字符串连接使用..运算符,支持自动类型转换
  5. 运算符优先级明确,但建议使用括号提高可读性

掌握这些运算符是编写高效Lua代码的基础。

基于 MIT 许可发布