#0 in Javascript: generate unique ID for a specific patcher instance (v8)

mathweasel's icon

I am trying to create a library that generates Global objects that are only shared within the same instance of a patcher.

What I am looking for is some unique ID similar to how "#0" is resolved in Max. In fact, having that exact ID would be great.

// Something like this
const thisPatcherId = resolveMaxHash("#0")
const g = new Global(thisPatcherId)

However, I can't seem to find a way to access this in Javascript without plumbing in #0 as an argument to the v8 object or generating objects on the fly which seems hacky:

/**
 * Hacky way to get #0 (patcher instance ID) in Javascript. Temporarily create:
 *
 * [i #0]
 *  |
 * [number]
 *
 * Then read the value of the number box.
 */
function getPatcherInstanceId(patcher) {
  const i = patcher.newdefault(0, 0, "i", "#0");
  const number = patcher.newdefault(0, 50, "number");
  patcher.connect(i, 0, number, 0);
  i.bang();
  const id = number.getvalueof();
  patcher.remove(i);
  patcher.remove(number);
  return id;
}

I was hoping this would be accessible on this.patcher somewhere, but I can't find any difference between this.max or this.patcher attributes between two instances of the same subpatcher.

TFL's icon

Object argument is the way to go:

[v8 code.js #0]

In code.js:

const unique_id = jsarguments[1];