Skip to content
LlamaLad7 edited this page Jul 9, 2024 · 5 revisions

Allows you to share values between handler methods in the same target method. This is generally preferable to storing the value in a field because this is thread-safe and does not consume any long-term memory.

You must provide an ID for the shared value and the annotated parameter's type must be one of the LocalRef family. The parameter's name is irrelevant and only the ID in the annotation is used to share matching values.

Possible parameters could look like:

  • @Share("fov") LocalDoubleRef fov
  • @Share("pos") LocalRef<BlockPos> pos
  • @Share("x") LocalIntRef x

The same reference objects will be passed to all handler methods requesting a given ID within a given target method invocation. By default, IDs are per-mixin, so you don't need to worry about including your modid or anything similar in them. If you specifically want to share values across mixins, set the namespace in the annotation to another value, e.g. your mod ID.

Note: If a @Shared value is read from before it has been written to, no exception is thrown and it will simply return the default value for that type (0, 0f, null, etc), much like a field.

Example

When targeting code such as the following:

public void targetMethod() {
	// ...
	this.renderSomething(someCalculation());
	// ...
}

you may wish to add some code at the end of the method that uses the renderSomething argument from earlier without recalculating it.

This could be done like so:

@ModifyArg(method = "targetMethod", at = @At(value = "INVOKE", target = "Lsome/package/TargetClass;renderSomething(I)V"))
private int saveRenderSomethingArg(int arg, @Share("arg") LocalIntRef argRef) {
	argRef.set(arg);
	return arg;
}

@Inject(method = "targetMethod", at = @At("TAIL"))
private void renderCustomThing(CallbackInfo ci, @Share("arg") LocalIntRef argRef) {
	this.renderSomethingCustom(argRef.get());
}

Your handler methods both receive the same argRef, so they can share the value properly.

Code Diff

  public void targetMethod() {
+ 	  LocalIntRef argRef = new LocalIntRefImpl(0);
  	  // ...
- 	  this.renderSomething(someCalculation());
+	  this.renderSomething(saveRenderSomethingArg(someCalculation(), argRef));
	  // ...
+ 	  renderCustomThing(new CallbackInfo(), argRef);
  }
Clone this wiki locally