Using and / or to simplify your code

I figured this out a while ago about the keywords and / or and I have found myself using it all the time to make better code; so today I have decided to spread the knowledge.

You probably haven’t thought that much about how and / or work but they actually work in a cool way.
I think explaining would be confusing; but coding would be simple so here is a code example of how they work.

--assume paramaters are like | a and b | a or b |

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

With them functioning this way you can do some pretty cool things.
Here’s one example I think that truly shows the power of this functionality;

Here is what you would do normally

assert(table[index], index .. " is not a valid index of table")
local v = table[index]

And here is what you can do using the recently provided knowledge:

local v = table[index] or error(index .. " is not a valid index of table")

Here is why the second one works:
If the index isn’t nil then the first argument (index) will be returned and error() wont be called.
If the index is nil then the second argument (error) will be returned and error() will be called.

Another useful use for this is a quick implementation of the ternary operation
Normal Code:

local Bool = true
local Value = 0

if Bool then
	Value = 10
end

But with the use of and / or you can do

local Bool = true
local Value = Bool and 10 or 0

(I will leave you to think about why this works)

I hope you enjoyed this and I bet you will find you using this to simplify your code all the time.

No, please don’t fake ternary only to “simplify” code, the conditionals matter and you may run into an unexpected case such as a and b or c where a is true and b is false, therefore evaluating to c when you are actually expecting the evaluation to be b.

If is provided as an assignment specifically to combat this case and provide a real way of effectively having ternary in Luau.

local foobar = if a == true then b else c

You should be using this instead now that it exists.

5 Likes

and or statements for ternary expression are outdated, luau has inline ifs now

4 Likes

Didn’t know there was that syntax but that is pretty cool.