Javascript function types and pass by reference?

When I put a function reference in an array object, what type should I give it if I want to invoke it? How would I do this?

array3;

Also why does javascript copy string variables, and how can you make it pass by reference?

Ex:
var bla : String = “aaa”
var ar : Array = new Array(“hello”, bla);
ar[1]; // → “aaa”
bla = “bbb”;
ar[1]; // → “aaa”, not “bbb”

Not sure if you can cast an object to a function after the fact. If it’s possible, I’d love to know how to do it!

But the following seems to work:

var myfunctions : Function[];
function sum(n1 : float, n2 : float){return n1+n2;}
function subtract(n1 : float, n2 : float){return n1-n2;}
myfunctions = Array(sum, subtract);

function Update () {
	Debug.Log(myfunctions[0](66,33)+" "+myfunctions[1](200,150));
}

I figured it out… use ‘as Function’.

function sum(n1 : float, n2 : float){return n1+n2;}
function subtract(n1 : float, n2 : float){return n1-n2;}
var myfunctions = Array(sum, subtract);

function Update () {
	var answer = (myfunctions[0] as Function)(23,19);
	Debug.Log(answer);
}

Hey it works, thanks!

Also why does javascript copy string variables, and how can you make it pass by reference?

Ex:
var bla : String = “aaa”
var ar : Array = new Array(“hello”, bla);
ar[1]; // → “aaa”
bla = “bbb”;
ar[1]; // → “aaa”, not “bbb”

strings on assignement generate a new string and drops the old.
Strings are never replaced internally unless you work with the buffers themself making, the strings quite a bit slower.

Yeah, that makes sense dream.

It’s good to know that you can do that, but is there any direct function variable type that I can use to store functions in objects? Or do i have to leave them as “Object” variables and just cast whenever I want to call them?

I guess internally JS wraps them up to Delegates, which represent typesafe and function header safe “method objects”

As for the storing functions in variables in order to execute them through the proxy variable, this will surely be of help:

http://forum.unity3d.com/threads/47765-delegates-function-pointers?p=604322&viewfull=1#post604322

As for strings being passed by reference (like a C char string[ ] pointer), rather than being assigned, I don’t really know, if if I had to guess I’d say it’s not possible at least without digging deeper into the .Net String class.

HTH!

  • jmpp