Skip to content

Command Argument Constraints

Redempt edited this page Nov 26, 2021 · 3 revisions

Sometimes, the type of an argument just isn't specific enough. You will occasionally need to limit a type further. A common example is limiting numeric inputs to be within a certain range. With Command Argument Constraints, this is incredibly simple.

There are built-in constraints for all of the numeric types already. If you want to limit the range of an int argument, you can do so like this:

example int<1,100>:num {
	help Example
	hook example
}

This will limit the range of inputs for the num argument to be numbers from 1 to 100. You can additionally use constraints like <,100> and <100,> to limit to ranges up to a number, or above a number, respectively. Constraints can also apply to flags, like int<1,100>:--num.

You can also define constraints for your own argument types. To do so, just call constraint on a defined ArgType. For example, you might want to make an ArgType for World which allows you to constrain which environments can be selected with a given command. Here's how that would look:

ArgType<World> worldType = new ArgType<>("world", Bukkit::getWorld).tabStream(c -> Bukkit.getWorlds().stream().map(World::getName))
	.constraint(s -> {
	Environment env = Environment.valueOf(s.toUpperCase());
	return Constraint.of(ChatColor.RED + "World must be of type " + s, (sender, world) -> world.getType() == env);
});

The call to constraint is a lambda which takes in a string, read from the command file, and returns a Constraint object. The Constraint is constructed by calling Constraint.of and passing a string which will be shown when the constraint check fails, and a lambda to check the constraint given the sender and world. There are other variants of Constraint.of that allow for more flexibility, including generating an error message dependent on the sender and argument.

freeze world<nether>:world {
	help Freeze a world
	hook freeze
}

Now, this command will only be able to be run passing a nether world as an argument.

Clone this wiki locally