As we know parameters of functions are passed by value in languages like TIScript and JavaScript. Inside the function we can modify paramaters and their new values will not be seen outside the function.
Let’s say we need to implement function expand(rect, dx, dy) : rect
that should increase dimensions of the rectangle.
If the rect is an object then we will write something like this:
function expand(rect, dx, dy) { return { x: rect.x - dx, y: rect.y - dy, w: rect.w + 2*dx, h: rect.h + 2*dy }; }
Problem with this implementation: it allocates brand new object on each call. That is not desirable if the function is used frequently.
If TIScript would support pass-by-reference for parameters then this function will have signature like this: inset(&x, &y, &w, &h, dx, dy) but no such thing as pass-by-reference in JS and TIScript for many good reasons.
As a solution: in TIScript we can use so called multi-return and multi-assignment feature – function is allowed to return multiple values.
Using this feature we can rewrite our function as:
function expand( x, y, w, h , dx, dy) { return ( rect.x - dx, rect.y - dy, rect.w + 2*dx, rect.h + 2*dy ); // returns "list" or tuple if you wish of four values. }
To call such function and to get multiple values from it we will use list of values as an l-value expression:
var x = 10, y = 10, w = 100, h = 100; (x,y,w,h) = expand(x,y,w,h, 20, 20 );
Parameters and return values are passed using stack of the VM so this will not create additional payload for the heap manager.
And yet it is pretty convenient for other cases too. For example this:
var a = 10, b = 5; (a,b) = (b,a);
is how you can swap values of two variables.
Small feature but quite usefull.
Main challenge was to plug value lists into existing syntax of JavaScript. Implementation is quite simple.