Skip to content
Ayfri edited this page Feb 3, 2024 · 4 revisions

Macros

Macros recently added support for macros inside functions in Minecraft 1.20.2.

Using Macros

To define a macro, use the macro() function:

say("I'm gonna use the macro ${macro("foo")}")

Inside a Minecraft function:

function("my_function") {
	say("This is my macro: ${macro("bar")}")
}

When called, this will substitute the actual text of the macro.

You can also evaluate a list of macros and have fully dynamic commands:

eval("command", "arg1", "arg2")
// equals to minecraft code:
// $$(command) $(arg1) $(arg2)

Calling functions with macros

You can call a function with macros by using the new arguments argument.

function("my_function", arguments = nbt { this["bar"] = "baz" })

That can also be a DataArgument (block position/entity selector/storage).

function(
	"my_function",
	arguments = allEntities {
		type = EntityTypes.MARKER
		name = "test"
	},
	path = "data.test" // optional path is available
)

Defining Macro Classes

For more complex macro usage, you can create a Macros subclass to define your macros:

class MyMacros : Macros() {
	val myMacro by "my_macro"
}

Then pass an instance to your function:

function("my_function", ::MyMacros) {
	say(macros.myMacro)
} 

Now you can access the macros on the macros property.

This also allows validating macros that are required when calling the function with an NBT Compound.

Best Practice

When using macros, you can create a function with arguments that calls the function with the macros:

fun main() {
	dataPack {
		function("teleport_to_spawn") {
			teleport(player(macro("player")), vec3())
		}
	}
}

fun Function.teleportToSpawn(player: String) {
	function("teleport_to_spawn", arguments = nbt { this["player"] = player })
}

Then you can call this function with your argument as a macro:

teleportToSpawn("jeb_")
Clone this wiki locally