- Home /
assigned function declaration in unity javascript for different types
In defining functions as function objects like this:
var firstone = function(a,b){ return a; }; var addition = function(a,b){ return a + b; };
firstone(1,2); // returns 1, as expected
Error occurs for `addition`: BCE0051: Operator '+' cannot be used with a left hand side of type 'Object' and a right hand side of type 'Object'.
Explicitly declaring the parameters as integer works:
var addition = function(a:int,b:int){ return a + b; };
However, is there a way to generalize this to work for floats and other data types?
Answer by hoffmanuel · Nov 07, 2012 at 08:36 AM
I don't know if it works with javascript, but with C# you can work with templates, which would make that possible. C# reference: link
Maybe you find someting for javascript
A template or generic function in c# can take different types in the function calls depending on how they are called. You can specialize the functions for specific types or let it be general.
Example (C#, i am not working with javascript, sorry):
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
You call this function like:
int intValue1 = 3;
int intValue2 = 7;
Swap<int>(ref intValue1, ref intValue2);