Having an "and" in a variable

I have seen many people put and in their variables like so:

local colour = 'Blue' and 'Red'

What does it mean to have and in variables?

you can use this in a few different ways with or etc

something like

local Testcolour = nil
local colour = Testcolour and 'Red' or 'Blue'

since Testcolour is nil it sets to blue
but if testcolour was a valid variable it would set to red

local Testcolour = true
local colour = Testcolour and 'Red' or 'Blue'

and this one would set to blue since it is valid if it was nil it would set to red

local Testcolour = 'Blue'
local colour = Testcolour or 'Red'

Oh so its like an if statement in a variable then right?

1 Like

WEll, yes and no.
It’s like a semi “requirement” of both things

You should use proper ternary operators for that. The and-or idiom has a nasty side effect of always returning the last value if the second one is “falsely”. Observe:

local value = true and false or true --this will become true
local value = if true then false else true --this will become false
2 Likes

Not exactly. The AND operator evaluates from left → right and will terminate once a certain condition is met.

The Lua documentation goes over this more in-depth.

Programming in Lua : 3.3

Also called short-circuiting. It is very important for error catching.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.