optional
inline fun <S, D : ArgumentDescriptor<*>> ArgumentBuilder<S, *>.optional(constructor: ArgumentConstructor<S, *, D>, action: ArgumentBuilder<S, *>.(ArgumentAccessor<S, D>?) -> Unit)
Content copied to clipboard
Registers the argument specified by the constructor as an optional argument and further configures the resulting subcommands with the given action.
The action is called once on the argument's builder, and once on the parent builder, creating a branching path.
On the path where the argument is present, the accessor passed to action is not null
and can be used on a CommandContext within an execute block to obtain an ArgumentReader for this argument.
On the path where the argument is not present, the argument passed to action is instead null
.
Author
Cypher121
Samples
import com.mojang.brigadier.CommandDispatcher
import net.minecraft.command.argument.PosArgument
import net.minecraft.command.argument.Vec3ArgumentType
import net.minecraft.network.MessageType
import net.minecraft.server.command.ServerCommandSource
import net.minecraft.text.Text
import net.minecraft.util.math.Vec3d
import org.quiltmc.qkl.wrapper.minecraft.brigadier.*
import org.quiltmc.qkl.wrapper.minecraft.brigadier.argument.*
import org.quiltmc.qkl.wrapper.minecraft.brigadier.util.entity
import org.quiltmc.qkl.wrapper.minecraft.brigadier.util.required
import org.quiltmc.qkl.wrapper.minecraft.brigadier.util.sendFeedback
import org.quiltmc.qkl.wrapper.minecraft.brigadier.util.server
import kotlin.random.Random
fun main() {
//sampleStart
dispatcher.register("slap") {
optional(player("target")) { target ->
optional(
enum(
"weapon",
mapOf(
"fish" to "a fish",
"book" to "an entire book"
)
)
) { getWeapon ->
optional(literal("repeatedly")) { repeatedly ->
execute {
//operator access is nullable only for optionals
val targetName = this[target]?.value()?.displayName ?: Text.literal("themselves")
server.playerManager.broadcastSystemMessage(
Text.empty().apply {
append(entity?.displayName ?: Text.literal("Someone"))
append(Text.literal(" slaps "))
append(targetName)
//checking the accessor directly works as well
if (getWeapon != null) {
append(Text.literal(" with ${getWeapon().value()}"))
}
if (repeatedly != null) {
append(Text.literal(" repeatedly"))
}
},
MessageType.SAY_COMMAND
)
}
}
}
}
}
//sampleEnd
}