This is like an extension of my past question, but I'd like to expand on it further.
As the title suggests, I'm wondering if an if statement will be able to make a decisive decision when faced w/ parentheses when handling values; a bit confusing, so I'll provide code for what I mean:
local ExampleVariable = nil local CompareNumberValue = 1 if CompareNumberValue == (ExampleVariable or 1) then -- This is what I mean print('It worked! :O') else print('Didn\'t work :/') end
In the past, and still present to this day, when you use multiple or's but don't repeat the value, it doesn't work:
local ExampleNumberValue = 0 if ExampleNumberValue == 1 or 6 or 8 then -- Obviously will fire, b/c 6 & 8 will return true, and aren't being compared to anything print('Waah...?') end
But w/ my raised question, will an if statement make a decisive decision when faced w/ parentheses?
EDIT
Well, just to be safe & ask, is this good practice to use? Or a good solution to some problems? And why would it as if value = var or num, the literal meaning for a sentence, instead of if value = var, then true, else num is true?
Parenthesis direct order-of-operations, but they don't impact the "meaning" of your code.
If you have code like
if foo == (bar or 1) then
this is of course the same as
local barp = bar or 1 if foo == barp then
I would recommend not embedding or
and and
used in this way in larger expressions.
It can easily get confusing.
Instead, save the result to a variable.
message = message or ""
I think you will find it is rather uncommon to need these inside conditions, though.
There are only really two times I ever use or
outside of using it on actual booleans:
function foo(blah) blah = blah or 0 print(blah) end
local count = wordCount[word] or 0
For most other cases I would prefer an actual if
.
I believe so. ExampleVariable
and 1
are contained within the parentheses, which should technically make it its own statement. Therefore, (ExampleVariable or 1)
should always return 1
.
EDIT: This is generally the way I would write my code:
local level --no need to declare, we want it nil for these purposes local defaultLevel=1 --if there's no level, we still want something to work with. local levelToUse=(level or defaultLevel) --get at least 1 value that isn't nil if levelToUse==1 then --use our value that is guaranteed to be a number print("User is on level 1") --print to output end --close the statement
Eh, if you say "or" it will only check the value after or if the previous value before or was issued as false, and also why do you have to ask? when you can experiment yourself...