Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Coldfusion support dynamic arguments?

In python there is the *args convention I am wondering if CF9 supports something similar.

Here is the python example

>>> def func(*args):
        for a in args:
               print a, "is a quality argument"


>>> func(1, 2, 3)
1 is a quality argument
2 is a quality argument
3 is a quality argument
>>> 
like image 698
John Avatar asked Nov 14 '11 15:11

John


2 Answers

Yes, CFML has supported dynamic arguments for as long as it has supported user-defined functions.

All arguments, whether explicitly defined, or whether passed in without being defined, exist in the Arguments scope.

The Arguments scope can be treated as both an array and a structure (key/value).


Here is the closest equivalent to your example, using script syntax:

function func()
{
        for (a in arguments)
               WriteOutput(arguments[a] & "is a quality argument");
}

Note that a in this example is the key name, not the value, hence why arguments[a] is used.

To be treated as code, the above script must either be within <cfscript>..</cfscript> tags, or alternatively inside a component {..} block inside a .cfc file.


Here's a couple of tag versions, the first equivalent to the for/in loop:

<cffunction name="func">
    <cfloop item="a" collection=#Arguments#>
        <cfoutput>#Arguments[a]# is a quality argument</cfoutput>
    </cfloop>
</cffunction>


And this one allows you to access the value directly (i.e. a is the value here):

<cffunction name="func">
    <cfloop index="a" array=#Arguments#>
        <cfoutput>#a# is a quality argument</cfoutput>
    </cfloop>
</cffunction>


In Railo* CFML, this last example can be expressed in script as:

function func()
{
    loop index="a" array=Arguments
    {
        WriteOutput(a & 'is a quality argument');
    }
}

*Railo is one of two Open Source alternatives to Adobe ColdFusion, the other being Open BlueDragon.

like image 78
Peter Boughton Avatar answered Nov 08 '22 03:11

Peter Boughton


Yes, arguments are passed into functions as an array called "arguments". In addition you can pass in an array called "argumentCollection" into a function.

public void function myFunct(){
    var myVar = "";

    if(arrayLen(arguments)){
        myVar = arguments[1];
    }
}

Invoking functions with dynamic arguments:

myFunc("hello","world");
  OR
myFunc(argumentCollection=["Hello","World"]);

Additionally you can extend arguments this way to have named arguments and arguments that are outside the named arguments:

public void function myFunction(String arg1){
  var secondArgument = "";

  if(arraylen(arguments) > 1){
    secondArgument = arguments[2];
  }
}

myFunction("Hello","World");
like image 38
bittersweetryan Avatar answered Nov 08 '22 01:11

bittersweetryan