Aller au contenu

Photo

Testing a Variable for True/False


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

#1
BelowTheBelt

BelowTheBelt
  • Members
  • 394 messages
I had a simple question about testing for TRUE/FALSE using variables.

So the code:
if(GetLocalInt(oPC)) is "true" if it returns any number and "false" if it returns 0.

if I assign a value to a variable in the code
int iVar = 47;
or
int iVar = TRUE;

Does the test:
if (iVar)
still return 'true'?

And does !!iVar test to see if iVar is 0/FALSE? 

My sense is that it does, but wanted to clarify.

Thanks!
 

#2
Lightfoot8

Lightfoot8
  • Members
  • 2 535 messages
NWN script and most High Level Languages do not check if something is TRUE in the compiled code. 0 (FASLE) is the only thing checked for. therefore 0 is FALSE and everything else is TRUE ( !=0 )

#3
BelowTheBelt

BelowTheBelt
  • Members
  • 394 messages
Ok, thanks for the clarification - it's testing for false or not false.

But to get to the question in the example above, i can declare a variable with a value and use the if statement to test for false/not false using the variable name, correct?

#4
Lightfoot8

Lightfoot8
  • Members
  • 2 535 messages
Correct,


If ( Expression )

The Expression in the if Statement can be anything that evaluates to a single integer. So any integer, function that returns an integer, comparison , or mat problem will do.

#5
BelowTheBelt

BelowTheBelt
  • Members
  • 394 messages
Excellent! Thanks for that. That's what I thought, though your explanation is more comprehensive than my understanding.

I see a lot of code that tests if (iVar == TRUE) in some of the code that I'm using (habd or the AI, for example) when it seems like if (iVar) would be sufficient and more efficient - especially in systems that are utilized frequently in the module.

While the efficiency gained might be minimal by removing any single instance of this in a module, it also seems that some efficiency can be gained by removing the unnecessary comparison module-wide.

#6
Tarot Redhand

Tarot Redhand
  • Members
  • 2 688 messages
It's mainly done like that for clarity and maintainability of the code. Personally I would use if(var) as it is clear enough for me.

TR