Optional Parameters

Hello All,

I am using the following code to see the use of optional parameters.

[COLOR=Red]
crRhombus(109,150,0x333311,0x556431,14);
function crRhombus(w:uint=10,h:uint=20,lclr:uint=0x990000,fclr:uint=0xff0000,lwid:uint=2)
{
var objHeight:uint = h;
var objWidth:uint = w;
var myRhohmbus:Sprite = new Sprite();

addChild(myRhohmbus);

myRhohmbus.x = 100;
myRhohmbus.y = 50;
// red triangle, starting at point 0, 0
myRhohmbus.graphics.lineStyle(lwid, lclr, 1);
myRhohmbus.graphics.beginFill(fclr);
myRhohmbus.graphics.moveTo(objWidth/2, 0);
myRhohmbus.graphics.lineTo(objWidth, objHeight);
myRhohmbus.graphics.lineTo(objWidth/2, objHeight*2);
myRhohmbus.graphics.lineTo(0, objHeight);
myRhohmbus.graphics.lineTo(objWidth/2, 0);
}

[COLOR=Black]So in the first line I am calling the function passing some parameter values. If I am skipping first parameter or any in between, then the code is not working. But if I am keeping sequence from first parameter to any last parameter, its working fine.

So my question is can I skip any parameter value from first or in between while calling the function. Please suggest.
[/COLOR][/COLOR]

You can’t skip. If you want to use the default value, you have to explicitly write the default value in your call, this especially for numbers. You can sometimes get away with this when using Object variables passing null which can work if the function is defined in a way to apply a default if the object passed is null.

Here it is working fine.

objNewDiamond.changeDimension(50, 100);

    public function changeDimension(nWidth:uint,nHeight:uint):void
    {
        setWidth(nWidth);
        setHeight(nHeight);
        resetDiamondStep();
    }

But if users somehow passes any one value like

objNewDiamond.changeDimension(50); or

objNewDiamond.changeDimension(50, );

It is showing error, advise how to put check for null parameters.

You can use the syntax as below:


function myFunction(a:Number, b:String="oops", c:uint=0)
{
//the a parameter is obligatory
//but you can skip b and c
//the default values will be used
trace(a,b,c)
}

myFunction(1, "and", 0) //output: 1 and 0
myFunction(5); //output: 5 oops 0

But you can’t skip the parameter in the middle: myFunction (0,4); //output: 0 4 0