JavaScript and Max: Functions and Arguments
So far, our js object can only respond to a bang, since the only thing in
our JavaScript code is a bang()
function. To have our js object respond
to integers and floats, we should add msg_int()
and msg_float()
functions
to our JavaScript code, respectively. These functions take one argument, which
will give us the value of the integer or float that was sent to the function.
As an example, let's have our js object add 5 to whatever number—integer or
float—comes in through its inlet. Here's what that code would look like.
function msg_int(i) {
outlet(0, i + 5);
}
function msg_float(f) {
outlet(0, f + 5);
}
If you'd like to send the js object a list of integers, rather than just
one, you should use the list
function.
outlets = 3;
function list(i, j, k) {
// Since Max objects typically send out messages in right-to-left order,
// it is good practice to follow that pattern in your JS objects.
outlet(2, k);
outlet(1, j);
outlet(0, i);
}
If you'd rather extract each element of the list one-by-one, you can get all of
the elements in the list at once by using the built-in arguments
variable,
which is represented internally as an array. Be careful though: if you try to
print the arguments
array as is, you'll get a very unhelpful message that
says jsobject
followed by some very large integer; this is because you're
printing the pointer to the array, not the array itself. To see each element
of the array, iterate through it with a for
loop.
function list() {
post(arguments); // this is totally unhelpful
post("\n");
var s = ""
for (var i = 0; i < arguments.length; i++) {
s += arguments[i] + " ";
}
post(s); // this is much better
post("\n");
}
Finally, it turns out you can send the js object any message, as long as
you have a corresponding outer-level function of the same name. You can find
two examples in the accompanying Max patch: one that performs basic math
operations on lists of integers, and another that stores a value and keeps
track of math operations sent to it.
In summary, you can begin planning out your JavaScript code by deciding what
Max messages you want to send to the js object. Then, write a series of
outer-level functions in JavaScript with names that correspond to those Max
messages: the first element of the Max message will be the function name, and
the rest of the elements of the message will be the function arguments.