Today I was talking with my friend and we found this.
local Count = 0
local Balls = {"Red", "Blue", "White"}
Count = Count > #Balls and 0 or Count
How work this Variable If Statement?
Today I was talking with my friend and we found this.
local Count = 0
local Balls = {"Red", "Blue", "White"}
Count = Count > #Balls and 0 or Count
How work this Variable If Statement?
I’ll try to break this down pretty simply.
#Balls
returns 3 because the Balls
table has 3 elements inside of it (“Red”, “Blue”, “White”).
Knowing this you can simplify the last line to this:
Count = Count > 3 and 0 or Count
If you substitute Count
for its value you get this:
Count = 0 > 3 and 0 or 0
But we can break this down even further.
0 > 3
is a comparison. It checks to see if 0
is greater than 3
. If it is it returns true, otherwise false.
So now we get this:
Count = false and 0 or 0
When you have a boolean (true or false) and then an and
and an or
statement after. It chooses which value based on the boolean. If the boolean is true it will choose the value after the and
, if it is false it will choose the one after or
.
This problem is a little strange because whether it is true or false, it always returns 0. Hope this helped.
So If I put this will work?
Swords = {"Wood Sword", "Iron Sword", "Elven Sword"}
Count = 4
Count = Count > #Swords and 3 or Count
Output: 3
Yes, correct. Since 4 is greater than 3 it returns the value after and
which is 3.
On top of what has been answered already, here are a few more notes.
Outside of our favorite scripting language here, these are called Ternary Operators.
The general syntax in the real world is this
condition ? choice_a : choice_b
In Lua, we can use these similar expressions because a string of conditions will always return the most recently evaluated condition if that makes any sense. For the purposes of my writing, ‘truthy’ means a value that is not false and not nil. For example, game.Workspace
is truthy. For all conditionals in Lua, such as while X do
and if X then
, they only require that X
be truthy for the condition to pass. Now onto how this works.
A and B or C
A
is evaluated first. If it is truthy, it needs to evaluate B
because and
requires both to be truthy. If B
is truthy, it is returned as the result of the string of conditions because or
does not need to be evaluated if both sides of and
are truthy. This also carries with it the caveat in which B
is not allowed to be false or nil, or else this ternary operation-lookalike will return C
every time.
If A
is false or nil, the other side of the and
does not matter so it will jump to the or
, and it will return C
regardless of whether C
is truthy. As I’ve mentioned, it returns the last part of the expression it checks, no matter what that part or its value is.