Complex logic statements?

Sometimes I see people using some complex logic statements to assign variables. The closest I could get to something similar is

local Condition = false
local Variable = "A" and Condition or "B"
print(Variable)

When Condition == false it prints B but when Condition == true it prints true and I am confused to oblivion

normally to get a similar result I do

local Condition = false
local Variable
if Condition then
    Variable = "A"
else
    Variable = "B"
end
print(Variable)

I can’t find any articles or posts talking about this so if someone could like an article or do a quick explanation I would appreciate it!

1 Like

You got the order wrong. The a and b or c idiom is meant to mock C’s conditional operator (a ? b : c).

What you wanted was Condition and "A" or "B"

4 Likes

It’s just how those keywords work

local var = cond == true and 0 or str

whenever cond == true as well as the condition after the and before the or, the second value (0) is passed instead of the first, and when the entire condition on the left hand equates to false:

local var = (cond == true and 0) or str -- the brackets is one condition in the end, comprising of two evaluations

then the or keyword just does its job, the value (the string) on the other end is passed.

You can basically eliminate if statements and even run functions:

local n = 4
local function f() return n == 4 and "n = 4" or n end

print(cond and n < 3 or f())
-- code in original post
local Condition = false
local Variable
if Condition then
    Variable = "A"
else
    Variable = "B"
end
print(Variable)

-- can be converted to:
Variable = Condition and "A" or "B"

This probably doesn’t have any considerable benefit but I tend to not use if statements within my coding structures:

		s.Source = (notDefinedAsServices and source or "") .. (
			       
			            table.find(definedLabels, selectedClassLabel) and ""  
		            or  
			            not table.insert(definedLabels, selectedClassLabel)
		           
			            and totalDef 
		) .. (
			           not notDefinedAsServices and source or ""
		     )
		

Though using if s can simplify and make your code look more organized.

4 Likes

This might help you:

1 Like

I already know this stuff and it’s all written in the official roblox article anyways

I was asking about that specific syntax but thanks anyways!

Just a note, if you wanted to add even more conditions, something like

if Condition then
    Variable = "A"
elseif Condition2 then
    Variable = "B"
else
    Variable = "C"
end

you simply do

Condition and "A" or Condition2 and "B" or "C"

If you don’t want an else case, just remove the or "C", if you wanted more conditions, add more, yada yada.

5 Likes