-
Notifications
You must be signed in to change notification settings - Fork 0
SubCommands
Subcommands are used to define different behaviours for a command, whereas arguments are just variables. For example, let's consider a MoneyCommand
to manage the money of a player. We could have different usages :
-
/money {pseudo}: See the money of a player -
/money {pseudo} give {amount}: Give money to a player -
/money {pseudo} take {amount}: Take money from a player
Here, pseudo and amount are arguments, whereas give and take are sub commands. We will keep the same example in the rest of this page.
A subcommand can itself have subcommands. This behaviour is recursive, so you can have as many layers as you want.
@Command(description = "Manage a player's money",
// Define one argument common to all subcommands
args = @Argument(value = "player", clazz = MyPlayerArgument.class))
class MoneyCommand extends CommandContext {
// Declare a subcommand
@Command(description = "Give money to the player")
void give(@Argument("amount") IntegerArgument amount,
@Env(key = "player") MyPlayer player)
{
player.giveMoney(amount.get());
}
// Main behaviour if no subcommand is called
@CommandBody
void showMoney(CommandSender sender, @Env(label = "player") MyPlayer player)
{
sender.sendMessage("money: " + player.getMoney());
}
}We start by defining the command with an argument of a custom type MyPlayerArgument at class level, that way the argument will be used for every subcommands as well as for the command body.
Then, we declare a method annotated with @Command to make it a sub command. It can recover the value of the player argument, and define a new argument for the amount of money to give.
It is also possible to annotate static inner classes with @Command to make them sub commands, so that themselves can have sub commands. It also works for top-level classes, in which case you have to use the subCommands parameter on the @Command annotation of the MoneyCommand to list all external classes that should be used as sub commands.
Example:
@Command(subCommands = MySubCommand.class)
class MyCommand extends CommandContext {
// ...
@Command
public static class MyOtherSubCommand {
}
}