Switch
Switch
Switch is often used when there are multiple limited outcomes for a single variable.
The Switch function can often be replaced by lots of "If" and "Else If" statements, but Switch is more efficient when the variable being checked has a limited amount of outcomes.
How to use "Switch".
Switch can be quite hard to understand at first glance, but after using it, it will become easier.
Here is an example of how it is used. This is taken from the menu scripts, which handles the ingame menus, I have cut the code and also added the commented lines myself.
self waittill("menuresponse", menu, response);
switch(response) { case "changeweapon": self closeMenu(); self closeInGameMenu(); if(self.pers["team"] == "allies") self openMenu(game["menu_weapon_allies"]); else if(self.pers["team"] == "axis") self openMenu(game["menu_weapon_axis"]); break;
case "changeteam": self closeMenu(); self closeInGameMenu(); self openMenu(game["menu_team"]); break;
case "muteplayer": self closeMenu(); self closeInGameMenu(); self openMenu(game["menu_muteplayer"]); break;
case "callvote": self closeMenu(); self closeInGameMenu(); self openMenu(game["menu_callvote"]); break; //default: // Add default here // break; }
The first part of the code is where the variable is defined. The game waits until a menu has been activated. The variables recieved are "menu" (the name of the menu activated) and "response" (what option was chosen from the menu). "Response" is the key variable for the 'Switch'.
After the variables have been defined, the Switch function is called. It then checks every "Case" (case is the term used for the possible outcomes of the variable) to find a match, if no match is found, the "Default" case is used. (If you do not have a Default case, the script will continue passed the 'Switch' function).
If a match is found, then the function will do ALL the events from that point onwards, which is why you MUST add "break;" at the end of every case, if the break is not existent, then all other case functions will run also.
To use the above example, I shall input my own values to show how the example works...
When I open the menu ingame, I choose the option "changeteam". The code kicks in and the variable "response" becomes equal to "changeteam". The switch statement will now look at every case for a positive match.
Once the match is found, everything after the case will happen:
- self closeMenu(); (Current menu closes)
- self closeInGameMenu(); (Close any other ingame menus)
- self openMenu(game["menu_team"]); (Will open the team menu).
- break; (The rest of the switch statement is ended and the code continues.