Skip to content

Argument Subtypes

Redempt edited this page Nov 27, 2021 · 2 revisions

Arguments aren't always standalone. At times, you will need arguments which rely on other arguments for resolving objects and supplying tab completions. Argument Subtypes are the solution to this problem.

Creating an Argument Subtype is very simple: First, you need a parent type. Then you call subType on it to create an ArgSubtype, which can then be passed into CommandParser#setArgTypes like a regular ArgType would be. An example of when this might be needed is if you have a home system: Each player can define their own homes with various names. You want an admin command allowing you to teleport to other players' homes, so you need to get the player as an argument, and the home belonging to that player as a separate argument. Here is a simple setup demonstrating how that might work:

private Map<UUID, Map<String, Location>> homes = new HashMap<>();

@Override
public void onEnable() {
	ArgType<Location> homeType = ArgType.getDefault("player").subType("home", (c, p, s) -> homes.get(p.getUniqueId()).get(s))
			.tabStream((c, p, s) -> homes.getOrDefault(p.getUniqueId(), new HashMap<>()).keySet().stream());
	
	new CommandParser(getResource("command.txt")).setArgTypes(homeType).parse().register("test", this);
}

Here, you can see how the subtype is created with tab completion. In order to use this in the command file, you would need to have the home subtype always appear immediately after an argument with the player type:

sethome string:name {
	help Sets a home
	hook sethome
	user player
}
tphome player:player home:home {
	help Teleports to another player's home
	hook tphome
	user player
}

From here, it is treated just as you would expect any argument to be. It will even work if you make the player argument optional like this:

tphome player:player?(context self) home:home {
	help Teleports to another player's home
	hook tphome
	user player
}

As long as the previous value will always exist, the subtype will be satisfied. This would ensure that, if no player is specified, it will teleport to the sender's home with the given name.

Clone this wiki locally