Function Pointer (Reference)

How does UnityScript handle function references? Is it exactly the same as ECMAScript/Javascript?
For instance, in C, one could:

#include <stdio.h>
void do_something(int x)
{
    // does something
}


int main()
{
    void (*foo)(int);
    foo = &do_something;

    foo( 2 ); //does something
}

Is this possible in UnityScript?

function do_something()
{
    // does something
}
function Start()
{
    var foo : function = do_something;

    foo(2); //does something
}

Is this valid code?

As far as I know, UnityScript doesn’t support delegates, events and lambdas, so there’s no way to do want you want. You should use C# instead.

I don’t buy that. It’s pretty standard ECMAScript. Not to mention the code compiles fine.

You can use delegates (and events) in C#, which is what I use with Unity.

Incorrect.

Well, Unityscript doesn’t really have anything to do with ECMAScript at this point, nor does the code above compile in Unity.

Nope. Instead,

function Do_something()
{
    // does something
}
function Start()
{
    var foo : function() = Do_something;

    foo(); //does something
}

Note that

var foo = Do_something;

will work just as well due to type inference (which is not dynamic typing). You can’t do foo(2) since the function has no parameters. You can of course supply one:

function Do_something (x : int)
{
    Debug.Log (x);
}

function Start()
{
    var foo = Do_something;
    foo(2); //does something
}

If you need to specify the type in this case, it’s

var foo : function(int);

–Eric

Thanks for your reply Eric.

class DrawListElement_JS {
	var position : Vector2;
	var texture : Texture;
	var scale : float;
	var drawingFunction : function(Vector2, Texture2D, float);
}
for (var drawElement : DrawListElement_JS in drawList) {
    drawElement.drawingFunction(drawElement.position, drawElement.texture, drawElement.scale);
}

:stuck_out_tongue:

Just an option

#pragma strict

class ListElementBase
{
	var position : Vector2;
	var texture : Texture;
	var scale : float;

	function Draw() {}
}

class ListElementA extends ListElementBase
{
	function Draw() { Debug.Log("I'm A"); }
}

class ListElementB extends ListElementBase
{
	function Draw() { Debug.Log("I'm B"); }
}

class ListElementC extends ListElementBase
{
	function Draw() { Debug.Log("I'm C"); }
}

function Start()
{
	var list = [ListElementA(), ListElementB(), ListElementC()];
	for (var element : ListElementBase in list)
	{
		element.Draw();
	}
}