[Tutorial] Ternary operation
#1

TERNARY OPERATION
In this tutorial I will tell you about ternary operator.

In computer science, a ternary operator is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?:, which defines a conditional expression. Since this operator is often the only existing ternary operator in the language, it is sometimes simply referred to as "the ternary operator". In some languages, this operator is referred to as "the conditional operator" [...]

These operations are written as:
Code:
<condition> ? <first expression> : <second expression>
If the condition is true, returns value of the first expression, differently - the second returns.

For example:
PHP Code:
new 1;
new 
= (0) ? 3
It is possible to make a similar code with use of a condition of if:
PHP Code:
new j,
    
1;
if (
0)
{
    
2;
}
else
{
    
3;

Also you can use ternary operations with a strings:
PHP Code:
new 1;
print((
!= 0) ? ("Cat") : ("Dog")); 
Fixed: in modified copy of the Pawn compiler by Zeex [...] fixed bug. If you are using the modified compiler' Zeex, you can write as
PHP Code:
print((random(3) > "QWE" "ASD")); 
.. and if not
PHP Code:
print((random(3) > ? ("QWE") : ("ASD"))); 
WHERE TO USE?
Ternary operations should be used if the condition has two operands. Is if/else.
PHP Code:
SendClientMessage(playerid, -1, (random(20) == 7) ? (!"You are just a lucky!") : (!"You are a loser :c")); 
I will give an example of a simple command for establishment of level of health to the player.
PHP Code:
CMD:health(playeridparams[])
{
    new 
targetidFloat:health;
    if (
sscanf(params, !"uf"targetidFloat:health))
        return 
SendClientMessage(playerid, -1, !"Command: /health [player] [health]");
    new 
Float:current_value;
    
GetPlayerHealth(targetidcurrent_value);
    if (
SetPlayerHealth(targetid, ((health current_value) ? health current_value 10.0)) == 0)
        return 
SendClientMessage(playerid, -1, !"Player isn't connected.");
    return 
SendClientMessage(playerid, -1, !"You're changed health level to the player.");

... or to send a message to the chat.
PHP Code:
CMD:chat(playeridparams[])
{
    return ((
isnull(params)) ?
        
SendClientMessage(playerid, -1, !"Command: /chat [text]") :
            
SendClientMessageToAll(-1params)
    );

You can use ternary operation in ternary operation!
PHP Code:
printf("%d", (random(100) > (random(5) == 200 0) ? 2)); 
Thanks for reading my small tutorial.
English is not my native language
therefore can be are errors
Reply
#2

good job)
Reply
#3

Add this to your tutorial to remove all the fuss of using a ternary operator >
PHP Code:
#define TernaryOperator(%0,%1,%2) ((%0)?(%1):(%2)) 
and there you go, you can simply use it as TernaryOperator(check, iftrue, iffalse) without worrying about braces n stuff (Since pawn's compiler has a problem with ternary operators containing strings you could use it as %0?%1:%2 but you would encounter some problems, I suggest you to stick to that^^).
Reply
#4

You should explain where you can use this as well.
Reply
#5

Quote:
Originally Posted by PrO.GameR
View Post
Add this to your tutorial to remove all the fuss of using a ternary operator >
PHP Code:
#define TernaryOperator(%0,%1,%2) ((%0)?(%1):(%2)) 
and there you go, you can simply use it as TernaryOperator(check, iftrue, iffalse) without worrying about braces n stuff (Since pawn's compiler has a problem with ternary operators containing strings you could use it as %0?%1:%2 but you would encounter some problems, I suggest you to stick to that^^).
With all due respect, but that's rubbish. You're actually typing more than what actually get replaced, completely defeating the purpose of a macro. The ternary operator is universal and anyone's who's familiar with will instantly recognize it.
Reply
#6

Quote:
Originally Posted by PrO.GameR
View Post
Add this to your tutorial to remove all the fuss of using a ternary operator >
PHP Code:
#define TernaryOperator(%0,%1,%2) ((%0)?(%1):(%2)) 
and there you go, you can simply use it as TernaryOperator(check, iftrue, iffalse) without worrying about braces n stuff (Since pawn's compiler has a problem with ternary operators containing strings you could use it as %0?%1:%2 but you would encounter some problems, I suggest you to stick to that^^).
Sorry, but I don't want to add this to my tutorial. In this macro there is no need.

Quote:
Originally Posted by Pottus
View Post
You should explain where you can use this as well.
Okay. But ... If to understand the principle of operation of ternary operations, then it is possible to apply them anywhere. For example (click).
Reply
#7

Quote:
Originally Posted by Vince
View Post
With all due respect, but that's rubbish. You're actually typing more than what actually get replaced, completely defeating the purpose of a macro. The ternary operator is universal and anyone's who's familiar with will instantly recognize it.
I agree with it being rubbish of a macro but I kinda have a bunch of ternary in ternaries (kinda like a little switch, but can't use switch because of it can only compare a value to a constant) And it looks fucked up just because of the string problem I mentioned, Absolutely if it could be used like sth>sth1 ? "Yes" : sth==sth2 ? "No" : "Maybe"
sure I wouldn't need that but with a shitload of brackets needed to make that work for this compiler thats a no-go, let alone a 4th option (Just for example, I don't really use that many at least for strings but I still use double ternary occasionally.)

But I guess it's just a preference tho, I can follow everything but braces(? brackets? we call them parentheses) so ternary operators with brackets are actually a nightmare for me.
Reply
#8

Quote:
Originally Posted by PrO.GameR
View Post
Add this to your tutorial to remove all the fuss of using a ternary operator >
PHP Code:
#define TernaryOperator(%0,%1,%2) ((%0)?(%1):(%2)) 
and there you go, you can simply use it as TernaryOperator(check, iftrue, iffalse) without worrying about braces n stuff (Since pawn's compiler has a problem with ternary operators containing strings you could use it as %0?%1:%2 but you would encounter some problems, I suggest you to stick to that^^).
What about this ?
PHP Code:
main()
{
    new 
ab=1c;
    
? (>= ?  0) : (>= 4);
    
printf("a: '%i' b: '%i' - c : '%i'"abc);

This will print 3 so we can say b > a & b ≥ 1
Reply
#9

Untonyst почему нет в русской части этого материала? В интернете же и так мало на русском языке материалов по Pawn. Просьба сделать для русского раздела.
Не понимаю, почему многие русские скриптеры предпочитают выкладывать только на английском материал.
Я английский знаю плохо (это моя проблема, не спорю), поэтому опять сидеть с переводчиком не хочется как-то. Прям какое-то даже не уважение почувствовал, что этого нет в русской части.
Reply
#10

Quote:
Originally Posted by Diman777
View Post
Untonyst почему нет в русской части этого материала? В интернете же и так мало на русском языке материалов по Pawn. Просьба сделать для русского раздела.
Не понимаю, почему многие русские скриптеры предпочитают выкладывать только на английском материал.
Я английский знаю плохо (это моя проблема, не спорю), поэтому опять сидеть с переводчиком не хочется как-то. Прям какое-то даже не уважение почувствовал, что этого нет в русской части.
Инфа по этой есть в учебник от Daniel_Cortez, от того и не захотелось писать в русскую тему, а тут можно повыпендриваться)) Но если уж так надо, то могу написать.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)