What does and mean in this?

print(false and "f") --prints false

print(true and "f") --prints f

I have also seen this in sjr04’s how to make a raycasting gun.

	local intersection = result and result.Position or origin + direction

Can anybody explain please? Oh and, I understand or.

It’s kind of like a shorthand way of writing this:

if (result) then
intersection = result.Position
else
intersection = origin + direction
end

If the value of “result” is “nil”, it’s treated as if it were “false” in a boolean expression. When you use the operators and and or on non-boolean values, anything that is not nil will be treated as “true”.

Generally using w = x and y or z is the Roblox equivalent of a ternary operator you’d see in other languages: w = x ? y : z as it takes advantage of the way truthy values are resolved in conditional expressions in lua.

2 Likes

How I would read this is the following:

print(false and "f")

is the equivalent as

if (false == true) then
     print("f") -- this will never run
else
     print(false == true) -- this will always run
end

and

print(true and "f")

is the equivalent as

if (true == true) then
     print("f") -- this will always run
else
     print(true == true) -- this will never run
end

To be honest, I would not take shortcuts in case you decide to revisit your code. I would just write the full length. For the second part, I would read it like this:

local intersection = result and result.Position or origin + direction

is the equivalent of what @blokav has mentioned above, which I will write it down here for convenience:

if (result) then
     intersection = result.Position
else
     intersection = origin + direction
end

I have yet to see anyone mention the actual Luau ternary operator. There’s a pretty big difference with that; the traditional and-or idiom has an edge case of always returning the last value if the first one is “falsey”.

local a = true
local b = false
local c = true

print(a and b or c) --> true
print(if a then b else c) --> false

This happens because of how it interprets the expression with binary operators:

1. a and b or c --original expression
2. (a and b) or c --precedence (order of operations)
3. (true and false) or true --substitute the values
4. (false) or true --simplify the parentheses
5. true --final answer

So, generally, I would always use the actual ternary operator over the and-or idiom, unless you specifically desire the latter’s funny behavior. Also, the true ternary operator can easily accept elseifs:

print(if a then b elseif c then d elseif e then f else g)
1 Like