2015-01-20 12:59:05

Hi everyone,
I have a very stupid math question, possibly only related to bgt.

I am looking at various game examples and I see something like:
score += board[player_position].landed ? 5 : 10;
What do ? and : mean?
I'm sure it's something really simple... what does this line do exactly?

Thanks all

ReferenceError: Signature is not defined.

2015-01-20 15:40:29

that's actually not a stupid question, believe it or not.  Many programmers don't know what that does.
It's commonly called the ternary operator, or at least it is in common usage.  There is probably a more official name for it, but as it's the only operator that takes 3 operands ternary operator is pretty unambiguous.
Anyhow, it's a shorthand if statement:

expr ? true : false;

Evaluates to whatever true is if expr is true or whatever false is if expr is false.  If you wrote it out the long way:

if(expr) {
 variable =true;
} else {
 variable = false
}

I don't use it often, but that's probably because most of my expressions are already pretty long (o the joys of mathematical coding) and it's worth just breaking them up.  Also it lets me put in comments.
Perhaps the most common use is this line, which is usually abstracted behind a function:

var = var < 0 ? -var : var;

Also known as absolute value.

My Blog
Twitter: @ajhicks1992

2015-01-20 19:18:35

The operator is also called the conditional operator. I actually learned about this language in the concept of java and I instantly became in love with it.

I like to sleep, Sleep is good,
This is how I do it: Lie on a nice warm cozy bed, and dream dreams about how to rule the world!
Follow @TheGreatAthlon5 on twitter for humorous facts and game updates!
If you like my posts, thumb me up!

2015-01-21 09:25:42

thanks guys for clearing that up big_smile

ReferenceError: Signature is not defined.