lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, Feb 24, 2021, 5:19 AM Sean Conner <sean@conman.org> wrote:
  Also, "and" and "or" in Lua short-circut evaluation.

        if foo() and bar() then ... end

if foo() returns false, bar() is not called (because the rest of the
_expression_ can never be true)

        if foo() or bar() then ... end

if foo() returns true, bar() is never called (because the _expression_ as a
whole is true)

  -spc

Yes, that's understandable. Short-circuiting for `and` and `or` works because in Boolean algebra, we have:

        1 or A = 1
        0 and A = 0

for any Boolean value of A.

But, in case of `xor`, you need to evaluate both sides to get the result. For example, look at the way OP was doing `xor` from its textbook definition:

        (A and not B) or (not A and B)

Short circuit or not: You need to evaluate both of A and B. If A=1 then the `not B` is evaluated. If A=0 then `(not A and B)` and subsequently `B` is evaluated.


~smlckz