复合条件的否定写法冗长且易错:not (a and b) 被学员写成 not a and not b——德摩根定律说 not (a and b) 等价于 not a or not b,and 变 or 而不是保持 and。条件简化时忽略这一定律,逻辑悄然改变。错误场景:
if not (vip and online) then
print("不能领奖")
end
正确语义是"非VIP 或 不在线"任一即拦截,但很多学员会误写成 not vip and not online。
德摩根变换两条规则:not (a and b) = not a or not b;not (a or b) = not a and not b。and 与 or 在取反后互换。规范写法。示例代码如下:
local function canClaim(vip, online)
return not (vip and online) == false
end
local function isBlocked(vip, online)
return not vip or not online
end
isBlocked 是 not (vip and online) 的德摩根展开——不可领取(被拦截)等价于 非VIP 或 不在线。
三步验证:vip=true online=true 时 canClaim 为 true 且 isBlocked 为 false;vip=false online=true 时 canClaim 为 false 且 isBlocked 为 true;四种组合逐一遍历,两函数输出严格互补。
三条件复合的德摩根展开同理:not (a and b and c) = not a or not b or not c,展开后 or 链逐项取反。示例代码如下:
local function anyMissing(a, b, c)
return not a or not b or not c
end
anyMissing 任一参数缺失即 true,是"全部满足才通过"的否定形式。
全站技术干货持续更新:996 引擎 / Lua 实战帖,语法、参数与示例一篇讲透。进入文章地图 · 查看全部 →
【游戏】 一、业务场景:if dist 20 then rate = 0.5 end —— 距离折损的全部骨架。组队打宝有人…
【游戏】 一、业务场景:STOCK = STOCK - 1 —— 全服限量抢购的核心一行。限量 1000 件的活动因不验余量…
【语法】 一、抛坑提问:按"金币除以等级"的复合值排序,比较函数里每次都现算除法,n log n 次重复计算——装饰排序先把…
【语法】 一、抛坑提问:背包格子列表整体后移 2 格,末尾 2 件绕回头部,逐个搬移要写嵌套循环——三步反转法三次交换完成,…
【游戏】 一、业务场景:PROGRESS = 0 —— 任务重接的全部规则。讨伐祖玛教主 30 只的任务卡在 29 只想换路…
【语法】 一、隐蔽陷阱:嵌套盒子求总金币用递归,盒子层数不可控时调用栈随之失控;把递归改成显式栈循环,层数与内存占用从失控变…