Aller au contenu

Photo

if statements and using || inside of them


  • Veuillez vous connecter pour répondre
5 réponses à ce sujet

#1
JediMindTrix

JediMindTrix
  • Members
  • 283 messages

I circumvented this issue by changing my approach, but I my curiosity is killing me...

 

if (iCurrentAppearance == 4 && iItemType == BASE_ITEM_MAGICWAND || iItemType = BASE_ITEM_MAGICROD)
  {
   object oNewItem = CopyItemAndModify(oItem, ITEM_APPR_TYPE_WEAPON_MODEL, ITEM_APPR_WEAPON_MODEL_BOTTOM, 1, TRUE); //Cycle back to first color
   DestroyObject(oItem); //Delete original
  }

 

Why is it the above code block compiles just fine, but seems to ignore everything after || in practice?



#2
Proleric

Proleric
  • Members
  • 2 346 messages
The first issue is that the final term has = where you probably mean ==.

The second potential issue is that nwscript may not be evaluating the expression in the order you intend. I forget what the rules are. For safety, I always parenthesize every term, so that there's no ambiguity. I suspect you mean

if ((iCurrentAppearance == 4) && ((iItemType == BASE_ITEM_MAGICWAND) || (iItemType == BASE_ITEM_MAGICROD)))


#3
WhiZard

WhiZard
  • Members
  • 1 204 messages

Proleric has it right.

 

Your first line boils down to,

 

iItemType = BASE_ITEM_MAGICROD;

if(TRUE)

  {

  ...

  }

 

Basically the expression if(a&&b||c) becomes if( (a && b ) || c).  Thus if c is TRUE, which is the case since BASE_ITEM_MAGICROD is not 0, then the whole expression is true.

 

There is a slight further complication in that if ( a && b ) is TRUE, then c will not be evaluated, because the expression will always end up true, so iItemType will not be changed.



#4
meaglyn

meaglyn
  • Members
  • 807 messages

 

There is a slight further complication in that if ( a && b ) is TRUE, then c will not be evaluated, because the expression will always end up true, so iItemType will not be changed.

 

This part does not appear to be accurate with the default nwn compiler. DrMcCoy has shown some evidence that the short-circuit logic in the code generator is broken and does not always do the right thing.  What you describe is the way it's _supposed_ to work and is the way it works with the out of box compilers.  I have not poked at it further because I generally don't use that compiler much. This code snippet could be a good way to test it...



#5
WhiZard

WhiZard
  • Members
  • 1 204 messages

I tested and this part is accurate.  "c" is not executed, because a && b is already true.  However I did find that I needed to put parenthesis around c (i.e. (iItemType = BASE_ITEM_MAGICROD)) in order for the script to compile.



#6
meaglyn

meaglyn
  • Members
  • 807 messages

Yeah, you're right. I can't reproduce what DrMcCoy reported either... nevermind.  Should have tested it myself before I said anything :)