Tutorial10 Embedding data in patches

The keep class provides an example of simple data propogation between patching sessions:

public class keep extends MaxObject {
	
	private Atom[] stuff = null;
	private MaxPatcher patch = getParentPatcher();
	private MaxWindow window = patch.getWindow();
	boolean autobang = true;
	
	keep() {
		declareIO(1,1);
		declareAttribute("autobang");
		setInletAssist(0, "(anything) whatever is input is stored and saved with the patch");
		setOutletAssist(1, "info outlet");
		setOutletAssist(0, "(anything) outputs whatever is stored on bang");
	}
		
	private void setStuff(Atom[] a) {
		window.setDirty(true);
		stuff = a;
	}
	
	public void inlet(int i) {
		setStuff(new Atom[] {Atom.newAtom(i)});
	}
	
	public void inlet(float f) {
		setStuff(new Atom[] {Atom.newAtom(f)});
	}
	
	public void list(Atom[] a) {
		setStuff(a);
	}
	
	public void anything(String msg, Atom[] a) {
		setStuff(Atom.newAtom(msg, a));
	}
	
	public void bang() {
		outlet(0, stuff);
	}
	
	public void loadbang() {
		if (autobang)
			bang();
	}
	
	public void save() {
		embedMessage("list", stuff);
	}
}

keep maintains an array of Atoms in stuff. When an instance of the class receives new input, it is stored in stuff. The method we're interested in for the purposes of this tutorial is save. When the user saves a patcher, Max calls the save method for every mxj object. By default the method does nothing, but if it is overridden as in the class above, one can use the embedMessage method to embed messages into the patcher file that will be sent to the newly created object the next time patcher file is loaded off of the disk.

In the keep class' save method the embedMessage call embeds a "list" message with stuff as the argument. When the patch is loaded from the disk, the object will receive this message immediately after being instantiated. Therefore the list method willo be called with the old value of stuff as the argument, and this sets the value of stuff in the new object to whatever it was when the patch was last saved.

As in the case of loadbang or a class's constructor, output should not be triggered by any message stored in the patcher file. Doing so risks instability.