You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua布尔值赋值异常:两次调用函数结果不符合预期

Lua逻辑运算导致布尔值无法交替的原因分析

先明确Lua逻辑运算的核心规则

Lua里的and和or是短路求值,并且返回的是参与运算的操作数本身,不是强制转为布尔值(只有当操作数本身是布尔时才返回布尔)。


第一段代码的执行过程

初始值:local bool = false

第一次调用函数:

bool = bool and false or true
-- 等价于:false and false → false;接着 false or true → true
-- 最终bool被赋值为true

第二次调用函数:

bool = bool and false or true
-- 等价于:true and false → false;接着 false or true → true
-- 最终bool还是被赋值为true

不管调用多少次,只要进入bool and false就会得到false,后续false or true必然返回true,所以永远无法得到false。


第二段代码的执行过程

初始值:local bool = false

第一次调用函数:

bool = not bool and true or false
-- 等价于:not false → true;接着 true and true → true;最后 true or false → true
-- 最终bool被赋值为true

第二次调用函数:

bool = not bool and true or false
-- 等价于:not true → false;接着 false and true → false;最后 false or false → false
-- 最终bool被赋值为false

每次调用先通过not bool翻转布尔值,后续的and/or只是把翻转后的布尔值再转成对应的true/false,所以能实现交替效果。


内容的提问来源于stack exchange,提问作者kanohn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 01:10:28