java script in Max 4 Live: scope of variables, …

M's icon

Hi,

I am coding in java script (Max 4 Live, Max 8 , Live 11) and it seems that global variables not only global within a script itself or the max device where the script is placed but also in the whole song for several js scripts.

Is this right? Are there any official notes regarding this?

Does it mean that all my functions and global variables must have unique names and it could be exist conflicts with other developers devices when using their devices?

Is there a way to make it only max device or script global?

tyler mazaika's icon

/*
This is "global" all throughout Live/different M4L devices.  
Could conflict with other devices/developer's stuff.
*/
accessibleeverywhere = 10


/*
This is accessible in the context of the local script and local functions, since 
it is declared outside of a function.
*/
var anywhereinscript = 20


function foo() {
	// This is only in this function
     var localtofunction = 30
}


/*
The Max JS Global() object type allows *scoped* sharing of values between multiple JS instances and also Max.
*/
var g = new Global("jsGlobal") 
g.arbitraryproperty1 = 40
g.arbitraryproperty2 = 50


/*
Assume the #1 argument to this JS (e.g. jsargument[1]) is a device specific name like "---myDevice".

This gives you a way to reference a device-specific scope for variables that you can use 
in multiple JS / Max objects.
Note that hardcoding "---myDevice" instead of jsarguments[1] won't work, 
because the "---" magic doesn't happen inside JS scripts.
*/
var devicespace = new Global( jsarguments[1] )
devicespace.something = 60


/*
But you could also use a Dict() in a similar way, which may be easier to interface with Max code.
*/
var d = new Dict( jsarguments[1] + "-dict" )
d.replace("something", 70)

M's icon

Thank you very much for this detailed answer.

I noticed I used the both first kinds and therefore have this global effect.

I don’t understand all of your explanation but my conclusion ist that global elements are common/acceptable and because of timing issues on my send/receiver topic I tend to global variables for communication