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.