-
-
Notifications
You must be signed in to change notification settings - Fork 15
Switch Case
ooOOoo Switch Cases have made their way to SkBee.
What are they? Well... you're about to find out.
A switch case is meant to be a short form of if/else if/else sections.
In short, you switch a single object, and you use cases to compare to the object you switched.
A case is not a condition though, it's just an object you are comparing.
Think of switch/case always being the equivalent of if a = b:
Let's look at a quick example:
on damage:
switch victim:
case sheep:
broadcast "SHEEP"
case cow:
broadcast "COW"
default:
broadcast "Something else"
Here we are switching the entity that was damaged, and using cases to compare it.
This code is exactly the same as doing:
on damage:
if victim is a sheep:
broadcast "SHEEP"
else if victim is a cow:
broadcast "COW"
else:
broadcast "Something else"
Just like an if/else if/else system, just the section of the case that matches will execute.
Inline cases allow you to run code in one line without a section.
Let's look at an example, using the same example from above, but with inline cases:
on damage:
switch victim:
case sheep -> broadcast "SHEEP"
case cow -> broadcast "COW"
default -> broadcast "Something else"
This works the same way as the one above, but rather than using a section, you can do it all in one line.
Normal switch cases will run code, but we can also use switch cases to return an object in a shorter form.
Let's look at an example:
on break:
set {_i} to switch return type of event-block:
case dirt:
return 1 of diamond
case stone:
return 1 of emerald
default:
return 1 of stick
give {_i} to player
And now let's compare that to a vanilla Skript example:
on break:
if event-block is dirt:
set {_i} to 1 of diamond
else if event-block is stone:
set {_i} to 1 of emerald
else:
set {_i} to 1 of stick
give player {_i}
Just like inline cases to run code, we can use inline cases to return something in a returnable switch.
These are useful when all you need to do in the case is 1 line of code.
Example:
on break:
set {_i} to switch return type of event-block:
case dirt -> 1 of diamond
case stone -> 1 of emerald
default -> 1 of stick
give {_i} to player
Cases support checking for multiple objects at once, let's take our example from above and modify it a bit:
on damage:
switch victim:
case sheep, cow, pig, chicken:
broadcast "Animal"
case zombie, skeleton, creeper:
broadcast "Monster"
default:
broadcast "Something else"
Let's look at the same example but with inline cases:
on damage:
switch victim:
case sheep, cow, pig, chicken -> broadcast "Animal"
case zombie, skeleton, creeper -> broadcast "Monster"
default -> broadcast "Something else"
-
default
should always go last. If you put default before a case, all cases after it will get ignored. - Cases will always run in order from top to bottom.