02.07.2014, 10:11
(
Last edited by BroZeus; 02/07/2014 at 02:33 PM.
)
Ternary Operators
--How Many Types of operator are there?
Basically there are 3 types of operator, they are -->
-- Uniary Operators
Example-- a++ , --b ... etc.
All of us knows about this.
-- Binary Operators
Example -- << , >> etc.
You can learn about Binary operators here- https://sampforum.blast.hk/showthread.php?tid=177523
-- Ternary Operators
Example -- a = b<c ? 5 : 6; etc.
You will learn about them more in this tut.
Ternary operator and its Basic usage
Basically ternary operator are used in place of "if" and "else" statements. They consists of a "?" and a ":" sign.
It's Syntax
Basic syntax -- Condition ? Value1 : Value2
It returns "Value1" if Condition is true and returns "Value2" if Condition is false.
Using it
A simple code in "if" and "else"--
pawn Code:
new a;
if(b < c)
{
a=10;
}
else
{
a=5;
}
pawn Code:
new a = b<c ? 10 : 5;

Advanced Usage
Advanced usage of ternary operators is used in place of nested "if" and "else" statements
A piece of advanced piece of ternary operator looks something like this--
pawn Code:
new a = b<c ? m<n ? 7 : 10 : 60;

Don't worry we can make i will make it simpler for you
Look at the code now--
pawn Code:
new a = b<c ? ( m<n ? 7 : 10 ) : 60;
Well you can use it without round brackets() but it will make you confuse so recommended usage is using with round brackets()
So a comparison of above example with an nested "if" and "else" statement, so here is the above example in "if" and "else" statements--
pawn Code:
new a;
if(b<c)
{
if(m<n)
{
a = 7;
}
else
{
a = 10;
}
}
else
{
a = 60;
}
pawn Code:
new a = b<c ? m<n ? 7 : 10 : 60;
//OR
new a = b<c ? { m<n ? 7 : 10 } : 60;
A Big Thanks to Vince for showing this feature of Ternary operators
Examples-
pawn Code:
if(PlayerStats[playerid][pDrugSeeds]==true)return SendClientMessage(playerid, COLOR_RED,"You aren't growing any drug plants. Use /plant to grow one.");
else return SendClientMessage(playerid, COLOR_RED,"You aren't growing any drug plants. Get some seeds first!");
pawn Code:
return SendClientMessage(playerid, COLOR_RED, (PlayerStats[playerid][pDrugSeeds])
? ("You aren't growing any drug plants. Use /plant to grow one.")
: ("You aren't growing any drug plants. Get some seeds first!")
);

PS. My first tut.
