13.07.2016, 22:14
(
Last edited by Untonyst; 15/07/2016 at 11:17 AM.
)
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:
If the condition is true, returns value of the first expression, differently - the second returns.Code:<condition> ? <first expression> : <second expression>
For example:
It is possible to make a similar code with use of a condition of if:PHP Code:
new i = 1;
new j = (i > 0) ? 2 : 3;
Also you can use ternary operations with a strings:PHP Code:
new j,
i = 1;
if (i > 0)
{
j = 2;
}
else
{
j = 3;
}
Fixed: in modified copy of the Pawn compiler by Zeex [...] fixed bug. If you are using the modified compiler' Zeex, you can write asPHP Code:
new i = 1;
print((i != 0) ? ("Cat") : ("Dog"));
.. and if notPHP Code:
print((random(3) > 0 ? "QWE" : "ASD"));
PHP Code:
print((random(3) > 0 ? ("QWE") : ("ASD")));
WHERE TO USE?
Ternary operations should be used if the condition has two operands. Is if/else. I will give an example of a simple command for establishment of level of health to the player.PHP Code:
SendClientMessage(playerid, -1, (random(20) == 7) ? (!"You are just a lucky!") : (!"You are a loser :c"));
... or to send a message to the chat.PHP Code:
CMD:health(playerid, params[])
{
new targetid, Float:health;
if (sscanf(params, !"uf", targetid, Float:health))
return SendClientMessage(playerid, -1, !"Command: /health [player] [health]");
new Float:current_value;
GetPlayerHealth(targetid, current_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.");
}
You can use ternary operation in ternary operation!PHP Code:
CMD:chat(playerid, params[])
{
return ((isnull(params)) ?
SendClientMessage(playerid, -1, !"Command: /chat [text]") :
SendClientMessageToAll(-1, params)
);
}
PHP Code:
printf("%d", (random(100) > (random(5) == 0 ? 200 : 0) ? 1 : 2));
Thanks for reading my small tutorial.
English is not my native language
therefore can be are errors
English is not my native language
therefore can be are errors