Log in

View Full Version : OR in a IF statement, bug or expected failure?



Ardem
January 13th, 2017, 00:14
I came across a strange issue and I am 99% sure this worked initially when I created the code but has not after the last few updates, I do not know if this is an expect failure or a bug.

The code I had originally was


if realm.getValue() == "Essence" or "Essense" then
return -70;
else
return 0;
end

However regardless of what the value is in realm.getValue() it will always pass -70, which is incorrect if the realm value is "Mentalism" however the work around is the long way which i hate, as I feel the dirty with extra code writing.


if realm.getValue() == "Essence" then
return -70;
elseif realm.getValue() == "Essense" then
return -70;
else
return 0;


Now this works because when the realm value is "Mentalism" it returns 0, now this code sit in the window script code section not a lua file not sure if that makes a difference.

Admittedly also this is very much cutdown code just to get my point across.

Moon Wizard
January 13th, 2017, 00:17
Nothing has changed in the Lua engine within FG for many versions, since v3.0, I think. And then, the only change would be to bump the revision for Lua. So, I'm not sure why the code would behave differently.

However, based on what I know of Lua. The default interpretation of what you typed would be (realm.getValue() == "Essence") or ("Essense"), which would always return true.

Regards,
JPG

Trenloe
January 13th, 2017, 01:45
You need to specify realm.getValue() twice. As Moon Wizard says, it sees or "Essence" as a new comparison - the or operator splits up statements and the comparison of realm.getValue() is only against the first "Essence". You should use:


if realm.getValue() == "Essence" or realm.getValue() == "Essense" then

Zhern
January 13th, 2017, 03:25
Alternatively, if you are worried about someone misspelling the expected entry, you could always do a pattern match instead of evaluating for the entire string. Doing the pattern match would mean there would only need to be one check for realm.getValue(). You could do something like this, which should match a string that starts with Ess and 0 or more alphanumeric characters after that. Keep in mind, I didn't test this so might not have it completely correct, but it is more about demonstrating another way of evaluating the entry in that field.




if(string.match(realm.getValue,"^Ess%w*") then
doWork...
end

Ardem
January 13th, 2017, 22:38
thanks guys appreciate the help