Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify only some optional arguments when calling function in ColdFusion?

I have a ColdFusion function "foo" which takes three args, and the second two are optional:

<cffunction name="foo" access="public" returntype="any">
    <cfargument name="arg1" type="any" required="true" />
    <cfargument name="arg2" type="any" required="false" default="arg2" />
    <cfargument name="arg3" type="any" required="false" default="arg3" />

    ...

    <cfreturn whatever />
</cffunction>

I want to call foo, passing in arg1 and arg3, but leaving out arg2. I know that this is possible if I call the function using cfinvoke, but that syntax is really verbose and complicated. I have tried these two approaches, neither works:

<cfset somevar=foo(1, arg3=3) /> <!--- gives syntax error --->
<cfset somevar=foo(1, arg3:3) /> <!--- gives syntax error --->
like image 962
Kip Avatar asked Jul 01 '09 21:07

Kip


People also ask

How do you make an argument in a function optional?

You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.

Are function call arguments optional?

So, it is optional during a call. If a value is provided, it will overwrite the default value. Any number of arguments in a function can have a default value.

What is an optional argument in functions?

Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

What is an optional function?

By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.


2 Answers

You have to use named arguments throughout. You can't mix named and positional arguments as you can in some other languages.

<cfset somevar = foo(arg1=1, arg3=3) />   
like image 190
Patrick McElhaney Avatar answered Sep 27 '22 21:09

Patrick McElhaney


Or.. you can use ArgumentCollection

In CF9 or above...

<cfset somevar = foo(argumentCollection={arg1=1, arg3=3})>

In CF8 or above...

<cfset args = {arg1=1, arg3=3}>
<cfset somevar = foo(argumentCollection=args)>

If CF7 or below...

<cfset args = structNew()>
<cfset args.arg1 = 1>
<cfset args.arg3 = 3>
<cfset somevar = foo(argumentCollection=args)>
like image 45
Henry Avatar answered Sep 27 '22 20:09

Henry