Why/How does this work?

Hey, and thanks for reading in advance. Stupid question warning!

I learned by reading a few scripts made by my friends that you can enumerate a true/false statement to a number without needing an if/then block.

local bool = false
local number = 7

number = number + ((bool and 3) or 0)

-- is the same as --

if bool then
number += 3

How exactly does that evaluate to a number? Are there any other weird syntax shortcuts like this?
Sorry, not exactly a high-priority thread, just curious.

that is what you’d call an addition assign operator. The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible.

no im pretty sure its just luas version of ternary operators
“x = a and b or c”

This basically means:

local number = 7 -- number

if bool then -- ((bool
    number += 3 -- and 3)
    number += 0 -- or 0)

and in this case is the same as do or if, and or in this case is an else.

In words:

--number = number + ((        bool and 3        )                  or 0                 )
--number = number + ((if bool is true then add 3)     else if bool isn't true then add 0)

+= is just syntax sugar for variable = variable +:

number += 1

--// is the same as

number = number + 1

yes i was explaining the addition assignment operator as that was being used in the second comparison, but yes the ternary operator is also being used.

1 Like