【问题标题】:Boolean is not set correctly布尔值设置不正确
【发布时间】:2022-10-13 22:16:56
【问题描述】:

我今天正在编写脚本并陷入了一个问题。

为什么当我使用这个时:

local bool = false
function()
   bool = bool and false or true
end

如果我调用函数两次,布尔值两次都返回 true,而不是像我预期的那样返回 true 和 false。

但如果我使用:

local bool = false
function()
   bool = not bool and true or false
end

这样,布尔值就被正确地设置为 true 和 false。

为什么会发生?

【问题讨论】:

    标签: lua


    【解决方案1】:

    首先:Lua 中的运算符优先级是not > and > or。这意味着您的第一个表达式等同于(bool and false) or true。这将始终与bool or true 相同,后者将始终为true。您的第二个表达式相当于((not bool) and true) or false,相当于(not bool) or false,相当于not bool,显然与true不同。

    因此,您认为两个布尔表达式等价的假设是错误的。

    【讨论】:

      【解决方案2】:

      false and false or true 和 true and false or true 将永远是 true。

      true and true or false 将是 true,当再次调用时,false and true or false 将是 false。

      无论如何,该声明的结束确实没有理由。如果您尝试切换布尔值,您可以使用bool = not bool

      【讨论】:

      • 它不像我说的那样。如果我们使用: local bool = false bool = bool and false or true print(bool) bool = bool and false or true print(bool) 将打印 true 2x 次.. 但是如果我们使用: local bool = false bool = not bool true or false print(bool) bool = not bool and true or false print(bool) 将打印 true 和 false(正确)我需要使用这种方式,因为我需要调用一个函数两次,我在里面设置了 bool功能。我只是想知道为什么第一种方法不打印真假,它和第二种方法一样。
      • ...我告诉过你为什么。它与第二种方法不同。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多