This website will automatically convert ..
to … so thats the cause of the confusion
Also, I like to show the short circuit behavior though a function and visuals, I think it explains it well
function AND(a,b)
if a then
return b
else
return a
end
end
function OR(a,b)
if a then
return a
else
return b
end
end
The reason this behavior can be done can be seen visually
Imagine the truth table of an AND statement:
This is similar to a multiplication table, but for an AND statement
You can see how if a is false, there is no way the result of the AND statement could be true, its always false
As a result of this, Lua will just return a, or false, to make it simpler
You can also see how if a is true, then the result of the AND statement is completely dependent on whatever b is
If b is false, it returns false
If be is true, it returns true
Therefore, Lua will just return b to make it simpler
A similar but opposite concept applies to OR statements
If a is false, the output is completely dependent on b, so Lua returns b
If a is true, the output is always true, so Lua simply returns a, which is true
This concept is very cool and useful and I think its probably one of my favorite Lua features
You can use it to do all kinds of fancy stuff, primarily a ternary statement, in a single line:
local result = condition and X or Y
--this is the same thing, but removes confusion about order of operations
local result = (condition and X) or Y
If condition is false or nil, it will return X
If condition is NOT false or nil, it will return Y
This works because if condition is false or nil, it will simply return itself
Once it returns itself, it will then do condition or Y
, and it will return Y (or B) because condition is false or nil
If condition is true or exists, it will return X (the B term), which then gets compared with Y in X or Y
Because X is true or exists (Im assuming X and Y exist), it will always return X (or the A term)
You can use this to make sure stuff actually exists, you can use it to choose between different options based on a certain condition, and all kinds of stuff that would be super ugly in normal code
But yeah conditions epic