15.01.2014, 16:52
(
Last edited by [WA]iRonan; 16/01/2014 at 10:37 AM.
)
Introduction
As I have seen many people are using way too much if statements, while they could have used the switch.
The tutorial
A part of my own gamemode, which is using a switch statement:
WRONG:
pawn Code:
if (pStats[playerid][vip] == 1) SetPlayerColor(playerid, COLOR_VIP_BRONZE);
if (pStats[playerid][vip] == 2) SetPlayerColor(playerid, COLOR_VIP_SILVER);
if (pStats[playerid][vip] == 3) SetPlayerColor(playerid, COLOR_VIP_GOLD);
if (pStats[playerid][vip] == 4) SetPlayerColor(playerid, COLOR_VIP_DIAMOND);
else SetPlayerColor(playerid, COLOR_VIP_PLAYER);
pawn Code:
switch (pStats[playerid][vip]) // A way it can be used. An integer.
{
default: SetPlayerColor(playerid, COLOR_VIP_PLAYER); // If a player's level is 0 (normal player)
case 1: SetPlayerColor(playerid, COLOR_VIP_BRONZE); // If a player's level is 1 (Bronze VIP)
case 2: SetPlayerColor(playerid, COLOR_VIP_SILVER); // If a player's level is 2 (silver VIP)
case 3: SetPlayerColor(playerid, COLOR_VIP_GOLD); // If a player's level is 3 (gold VIP)
case 4: SetPlayerColor(playerid, COLOR_VIP_DIAMOND); // If a player's level is 4 (Diamond VIP)
}
Wrong: 5 Lines
Correct: 6 lines
As you can see the if statements are 5 lines, which is shorter than the switch. Although you should still use switch, read below why.
Quote:
Why? At "Wrong" the server keeps calling the player's stats over and over, which takes much data. While at "Correct" the server calls the player's stats only once, taking less data than the "wrong" code. |
pawn Code:
if(Cash >= 1500 && Cash <= 8000)
{
// do whatever
}
switch(Cash)
{
case 1500..8000:
{
// do whatever
}
}
This is a preview of that, if your if/else or case is over lets say 500, you should use the if & else statement as in that case the 'case' statement is slower.
Offcourse there is an easier way, saving you time although it's a bit harder to read than case and if/else statements.
(Thank you bigETI)
pawn Code:
static const vip_rank[] = {COLOR_VIP_PLAYER, COLOR_VIP_BRONZE, COLOR_VIP_SILVER, COLOR_VIP_GOLD, COLOR_VIP_DIAMOND};
SetPlayerColor(playerid, vip_rank[pStats[playerid][vip]]);
Additional pages:
https://sampwiki.blast.hk/wiki/Control_Structures#switch
https://sampwiki.blast.hk/wiki/Control_Structures#if
(Critism is allowed, some things might not be right. This is my first tutorial since age's and idea's are welcome.)