Function

Use the function requirement in a KubeJS recipe

A function requirement is a way to execute javascript code when a recipe is processing.

To do that 2 things are needed :

  • A method that will tell the recipe to send a KubeJS event when needed.

  • An event listener where the JS code will be put.

Both the recipe method and the event listener are linked using a String id.

Note: This has nothing to do with MC functions (or commands), this requirement allow you to make your own code in JavaScript and pass it to be executed by the machine.

In the recipe

//Executed when the machine is idle and search a recipe to process.
.requireFunctionToStart("id")

//Executed the first tick of the crafting process.
.requireFunctionOnStart("id")

//Executed each tick of the crafting process.
.requireFunctionEachTick("id")

//Executed the last tick of the crafting process.
.requireFunctionOnEnd("id")
  • The passed id MUST be a string.

  • Several functions can share the same id, but they will all share the same event too.

  • The function can be delayed, put .delay(delay) directly after any .requireFunctionXXX() call to make the function be executed at the specified delay.

In a server script (outside the recipe event)

CustomMachineryEvents.recipeFunction("id", event => {
  //Print the machine id in logs when the function is run.
  console.info(event.machine.id)

  //Immediately stop the function and allows the recipe to run.
  event.success()
  
  //Immediately stop the function and display an error in the machine.
  event.error("Error")
})
  • If neither event.success() nor event.error() are called the recipe will be allowed to run.

  • If event.error() is called without specifying an error message it will show the default one instead.

  • The event object contains several useful methods, see more on its dedicated wiki page.

Example :

ServerEvents.recipes(event => {
	event.recipes.custommachinery.custom_machine("custommachinery:power_crusher", 200)
	.requireFunctionEachTick("add_2_diamonds")
})

CustomMachineryEvents.recipeFunction("add_2_diamonds", event => {
	let remaining = event.machine.addItemToSlot("output1", "2x minecraft:diamond", true)

	if(remaining.count == 0) {
                event.machine.addItemToSlot("output1", "2x minecraft:diamond", false)
		event.success()
        }
	event.error("Can't add 2 diamonds in output slot")
})

Migrating from previous function requirement

Previously :

ServerEvents.recipes(event => {
	event.recipes.custommachinery.custom_machine("id", time)
	.requireFunctionXXX(ctx => {
		//Do code here
	})
})

Now :

ServerEvents.recipes(event => {
	event.recipes.custommachinery.custom_machine("id", time)
	.requireFunctionXXX("id")
})

CustomMachineryEvents.recipeFunction("id", event => {
  	//Do code here
  	//Use event.success() and event.error("error")
  	//instead of return ctx.success() and return ctx.error("error")
})

Last updated