not 运算符优先级引发的 bug 案例

解读

  1. 代码意图
    策划需求是“非战斗 且 未死亡”→ 瞬发;其余情况 → 普通释放。
  2. 实际行为
    Lua 的 not 优先级 高于 and,因此表达式被解析为
    (not inFight) and (not isDead),看起来似乎没问题。
    但上线后玩家反馈:死亡后仍然可以瞬发。
  3. 根因
    日志显示 GetUnitFlags 在部分网络延迟场景下返回了 nil 而不是布尔值。
    当 inFight == nil 时,not inFight 得到 true;
    当 isDead == nil 时,not isDead 也得到 true;
    于是 true and true → true,死亡玩家被错误地判定为可瞬发。
    简言之:优先级本身没错,但优先级放大了隐式类型转换带来的风险。
  4. 国内面试场景
    面试官常把“优先级”和“真假表”混在一起来考察候选人是否具备“防御式编程”意识;只背“not > and > or”却不考虑布尔校验的候选人会被直接降级。

知识点

  1. 运算符优先级(从高到低)
    not → ^ → * / // % → + - → .. → << >> → & → ~ → | → < > <= >= ~= == → and → or
    同级从左到右(除了 ^ 和 .. 右结合)。
  2. Lua 真假表
    只有 nil 与 false 为假,其余均为真;0、空字符串、空表都是真。
  3. 隐式类型转换风险
    函数返回 nil 时,not nil 为 true,极易被误当成“有效 false”使用。
  4. 防御式布尔校验惯用法
    local inFight = GetUnitFlags(unit) == true   -- 强制转布尔
    local isDead  = GetUnitFlags(unit) == true
    
    或封装为
    local function Bool(v) return v == true end
    
    也可直接用 !! 思路:local inFight = not not GetUnitFlags(unit)。
  5. 代码审查规范
    国内大厂 Lua 规范(腾讯、网易)强制要求:
    • 所有布尔语义变量必须显式 == true/== false 校验;
    • 复杂条件加括号,即使优先级足够;
    • 单元测试必须覆盖 nil、false、true 三态。

答案

bug 根因:
GetUnitFlags 在异常链路返回了 nil,而 not nil 为 true,导致“死亡”条件被逻辑反转,满足瞬发条件。

最小修复(保持优先级不变,加布尔校验):

local inFight, isDead = GetUnitFlags(unit)
-- 显式转成布尔,再取反
if not (inFight == true) and not (isDead == true) then
    InstantCast(skill)
else
    NormalCast(skill)
end

更简洁的写法(推荐):

local inFight, isDead = GetUnitFlags(unit)
inFight = inFight == true
isDead  = isDead  == true
if not inFight and not isDead then
    InstantCast(skill)
else
    NormalCast(skill)
end

拓展思考

  1. 如果策划需求改成“非战斗 或 未死亡”可瞬发,优先级会导致什么坑?
    表达式变成 not inFight or not isDead,由于 not 高于 or,解析仍为 (not inFight) or (not isDead),逻辑上恰好等价于 not (inFight and isDead),看似正确;但若 inFight/isDead 可能为 nil,仍需先转布尔,否则同样会出现 nil 被当成 true 的隐形 bug。
  2. 在性能敏感的战斗脚本里,显式 == true 会不会有开销?
    Lua 5.3/5.4 的 OP_EQ 指令与 OP_NOT 指令周期相同,现代 JIT(LuaJIT)会折叠常量,一次显式比较成本远低于一次 cache miss,因此可读性与安全性收益远大于性能损耗。
  3. 如何写单元测试来防止此类优先级+类型转换复合错误?
    使用 busted 或自研框架,构造三态参数表:
    {{inFight=nil,isDead=nil}, expect="Normal"},
    {{inFight=false,isDead=false}, expect="Instant"},
    {{inFight=true,isDead=nil}, expect="Normal"},
    
    通过持续集成每日跑千组随机组合,可 100% 拦截。