Lua 运算符
系统梳理 Lua 算术、关系(重点强调 ~=)、短路逻辑、字符串连接(..)与长度(#)四大类运算符,以及优先级与右结合性规则。
学完这一章,你能够
- 系统梳理 Lua 算术、关系(重点强调 ~=)、短路逻辑、字符串连接(..)与长度(#)四大类运算符,以及优先级与右结合性规则。
运算符分类与算术运算符
Lua 提供算术、关系、逻辑以及其他运算符四大核心类别(Lua 5.3+ 还新增了 `&`、`|`、`~`、`<<`、`>>` 位运算符)。算术运算符包括 `+`、`-`、`*`、`/`、`%`、`^`(乘幂)、一元负号 `-` 以及 Lua 5.3 起引入的向下取整除法 `//`(详见表 1)。需注意 `/` 始终执行浮点除法(如 `5 / 2` 得 `2.5`),而 `//` 执行整除(如 `5 // 2` 得 `2`)。
关系运算符与逻辑运算符
关系运算符用于比较两个值并返回 `boolean` 结果,包含 `==`、`~=`、`>`、`<`、`>=`、`<=`(详见表 2)。格外留意 Lua 的“不等于”写作 `~=` 而不是 C/Java/Python 中的 `!=`。
逻辑运算符包括 `and`、`or` 与 `not`(详见表 3)。`and` 与 `or` 采用短路求值并**返回实际操作数本身**而非强转布尔值:`a and b` 在 `a` 为假(`false` 或 `nil`)时直接返回 `a`,否则返回 `b`;`a or b` 在 `a` 为真时直接返回 `a`(因此 `0 or 99` 短路返回 `0`),否则返回 `b`;`not` 则始终返回布尔值 `true` 或 `false`。
其他运算符与运算符优先级
其他常用运算符为字符串连接符 `..` 与一元长度运算符 `#`(详见表 4):`a .. b` 将两段字符串拼接为新串,`#` 返回字符串的字节长度或序列型 `table` 的边界长度。
Lua 运算符优先级从高到低依次为:`^` > 一元 `not` / `-` / `#` > `*` / `/` / `//` / `%` > `+` / `-` > `..` > 关系运算符(`<` `>` `<=` `>=` `~=` `==`) > `and` > `or`。除乘幂 `^` 与连接符 `..` 为**右结合**外,其余二元运算符均为左结合,因此 `x ^ y ^ z` 等价于 `x ^ (y ^ z)`,而 `-x ^ 2` 因 `^` 优先级高于一元负号等价于 `-(x ^ 2)`。复杂算式中使用圆括号显式分组有助于消除歧义并提升可读性。
Lua 算术运算符一览(设 A = 10,B = 20)
| 操作符 | 运算说明 | 计算示例 |
| + | 加法运算 | A + B 结果为 30 |
| - | 减法运算 | A - B 结果为 -10 |
| * | 乘法运算 | A * B 结果为 200 |
| / | 浮点除法运算(保留小数) | B / A 结果为 2.0;5 / 2 为 2.5 |
| % | 取模(余数)运算 | B % A 结果为 0 |
| ^ | 乘幂运算(右结合) | A ^ 2 结果为 100.0 |
| - | 一元负号(取相反数) | -A 结果为 -10 |
| // | 整除运算(Lua 5.3+ 向下取整) | 5 // 2 结果为 2 |
Lua 关系运算符一览(设 A = 10,B = 20)
| 操作符 | 比较含义 | 求值示例 |
| == | 等于,相等返回 true,否则返回 false | (A == B) 为 false |
| ~= | 不等于(注意非 !=),不等返回 true | (A ~= B) 为 true |
| > | 大于,左操作数更大时返回 true | (A > B) 为 false |
| < | 小于,左操作数更小时返回 true | (A < B) 为 true |
| >= | 大于等于 | (A >= B) 为 false |
| <= | 小于等于 | (A <= B) 为 true |
Lua 逻辑运算符一览(设 A = true,B = false)
| 操作符 | 短路求值规则 | 求值示例 |
| and | 逻辑与:若 A 为假(false/nil)直接返回 A,否则返回 B | (A and B) 为 false |
| or | 逻辑或:若 A 为真直接返回 A,否则返回 B | (A or B) 为 true |
| not | 逻辑非:永远返回布尔值,对真值取反得 false,对假值取反得 true | not (A and B) 为 true |
Lua 连接与长度运算符一览
| 操作符 | 功能说明 | 使用示例 |
| .. | 连接两个字符串(右结合) | "Hello " .. "World" 结果为 "Hello World" |
| # | 一元长度运算符,返回字符串字节数或序列型 table 边界长度 | #"Hello" 返回 5 |
离线校验算术/整除、~= 关系比较、and/or 短路返回值与运算符右结合优先级
展开查看收起
"""Offline Lua 5.4 semantic verification lab for Chapter 10 (miscellaneous-operator)."""
import json
VERSION = "CPython 3.12.14 offline Lua 5.4 semantic verifier (lua interpreter absent)"
def lua_truthy(v):
return not (v is False or v is None)
def lua_and(a, b_fn):
return a if not lua_truthy(a) else b_fn()
def lua_or(a, b_fn):
return a if lua_truthy(a) else b_fn()
def case_arithmetic_and_floor_division():
a, b = 21, 10
expected = {
"add": 31,
"sub": 11,
"mul": 210,
"div": 2.1,
"mod": 1,
"pow": 441,
"unm": -21,
"five_div_two": 2.5,
"five_floordiv_two": 2,
}
actual = {
"add": a + b,
"sub": a - b,
"mul": a * b,
"div": a / b,
"mod": a % b,
"pow": a ** 2,
"unm": -a,
"five_div_two": 5 / 2,
"five_floordiv_two": 5 // 2,
}
return {
"name": "arithmetic_and_floor_division",
"summary": "校验算术运算符 + - * / % ^ 负号以及 Lua 5.3+ 整除 // 与浮点除法 / 的区别",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_relational_operators_tilde_eq():
a, b = 21, 10
a2, b2 = 5, 20
expected = {
"eq": False,
"neq_tilde": True,
"lt": False,
"gt": True,
"le_after": True,
"ge_after": True,
"lua_neq_token": "~=",
}
actual = {
"eq": a == b,
"neq_tilde": a != b,
"lt": a < b,
"gt": a > b,
"le_after": a2 <= b2,
"ge_after": b2 >= a2,
"lua_neq_token": "~=",
}
return {
"name": "relational_operators_tilde_eq",
"summary": "校验关系运算符 ==、~=(非 !=)、>、<、>=、<= 的布尔求值结果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_logical_short_circuit_value_return():
side_effect = []
def probe(val):
side_effect.append(val)
return val
r1 = lua_and(False, lambda: probe("skipped_and"))
r2 = lua_or(0, lambda: probe("skipped_or")) # 0 is truthy in Lua!
r3 = lua_or(None, lambda: probe("default_val"))
r4 = not lua_truthy(lua_and(False, lambda: True))
expected = {
"false_and_x": False,
"zero_or_x_short_circuits": 0,
"nil_or_default": "default_val",
"not_false_and_true": True,
"evaluated_probes": ["default_val"],
}
actual = {
"false_and_x": r1,
"zero_or_x_short_circuits": r2,
"nil_or_default": r3,
"not_false_and_true": r4,
"evaluated_probes": side_effect,
}
return {
"name": "logical_short_circuit_value_return",
"summary": "校验 and/or 短路求值并返回实际操作数(含 0 为真短路)及 not 逻辑非",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_concat_length_and_precedence():
a, b = "Hello ", "World"
# Right associativity of ^ : 2^3^2 == 2^(3^2) == 512, -2^2 == -(2^2) == -4
pow_right = 2 ** (3 ** 2)
neg_pow = -(2 ** 2)
x, y, z, w = 20, 10, 15, 5
e1 = (x + y) * z / w
e2 = ((x + y) * z) / w
e3 = (x + y) * (z / w)
e4 = x + (y * z) / w
expected = {
"concat": "Hello World",
"len_world": 5,
"len_test": 4,
"len_mbsky": 13,
"pow_right_assoc": 512,
"unary_minus_below_pow": -4,
"prec_results": [90.0, 90.0, 90.0, 50.0],
}
actual = {
"concat": a + b,
"len_world": len(b),
"len_test": len("Test"),
"len_mbsky": len("www.mbsky.com"),
"pow_right_assoc": pow_right,
"unary_minus_below_pow": neg_pow,
"prec_results": [e1, e2, e3, e4],
}
return {
"name": "concat_length_and_precedence",
"summary": "校验 .. 字符串连接、# 长度运算符、^ 与 .. 右结合性及四则括号优先级",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_arithmetic_and_floor_division(),
case_relational_operators_tilde_eq(),
case_logical_short_circuit_value_return(),
case_concat_length_and_precedence(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
当 `a` 为真但 `b` 恰好等于 `false` 或 `nil` 时,`a and b` 的结果是假值,接着 `or c` 会把结果求值为 `c` 而不是 `b`;因此仅在明确 `b` 不为 `false`/`nil` 时才能安全使用该写法。