Reusing a function

Admittedly, I am having trouble understanding how to reuse a function. I have a euclidean distance function that I am using a bunch in the onTouch script of a canvas:

function eucDistance(p1, p2) {
  var a = p1[0] - p2[0];
  var b = p1[1] - (1 - p2[1]);
  return Math.sqrt( a*a + b*b );

Right now, I am declaring the function in onTouch, but I assume that is the most horrible way to do it because if gets redefined on every inTouch call. But for the life of me, I cant figure out where and how to declare it once.

Thanks in advance.



You can declare it in onCreate like so

locals.eucDistance = function(p1, p2) {
  // etc

and use it in onTouch:

var d = locals.eucDistance()

Or if you're going to use it in many different widgets, you can declare it in the root's onCreate instead:

globals.eucDistance = function(){/*etc*/}

Note that the root's onCreate executes after its children have been parsed so using a function declared here in another onCreate script will error on session load,it can be circumvented by declaring the global function in a script widget instead. I'm also considering adding a scripting property to the root widget to safely do that, something like onBeforeCreate..

1 Like

Very helpful thank you. I had something close but messed up the syntax. Quick follow up question. Does globals extend to parents as well? I am hoping I can set up variables for root and children but not parent. Thanks!

The variable named globals is shared between all scripts, it's independent of the widget structure. If you want to define widget-scoped variables you can use setVar() and getVar():

// define in some onCreate script
setVar(this, 'foo', function() {
  // do something

// call somewhere else
// 'widget_id' is the id of the widget that called setVar
getVar('widget_id', 'foo')()

I see. Very helpful. Thanks!

hi there

very interesting !

i make a little json session file to test the points mentionned.

functions-globals-locals.json (8.1 KB)

i got a question :slight_smile:

it works !

but this below not

Any idea ?

getVar is only available in scripting properties, you need to use the appropriate advanced syntax here instead (VAR{}).

Edit: It goes without saying that using the globals object to smuggle functions such as this one in non-scripting properties won't work.

Hum the value property is not a scripting property right ? But the globals.add works ?!

If globals.add() doesn't call any scripting-specific function then yes.

Don't catch which functions you talk about ? Sorry

These : Scripting - Open Stage Control