CFLib.org – Common Function Library Project

OptArgType(args, index, type[, default])

Last updated August 20, 2002

author

Jordan Clark

Version: 1 | Requires: CF5 | Library: UtilityLib

Description:
This function is similar to optArg() except that it allows you to specify a type of the argument, if the provided arg isn't the correct type, then the default value is used. Also when types "structure" and "array" are used an empty array / struct is created when no default value is specified. This tag requires the typeOf() udf to work.

Return Values:
Returns a value (any type).

Example:

<cfscript>
function foo( p1 ) {
    var s = structNew();
    var p2 = optArgType( arguments, 2, "structure" );
    var p3 = optArgType( arguments, 3, "array", listToArray( "foo,bar,grill" ));

    s.p2 = p2;
    s.p3 = p3;
    return s;
}
</cfscript>
<cfdump var="#foo(1)#">

Parameters:

Name Description Required
args Arguments to check. Yes
index Index to check. Yes
type Type to use. Yes
default Value to use if args[index] doesn't exist. Defaults to an empty string if type isn't struct or array. No

Full UDF Source:

/**
 * Pass in an optional UDF argument of a specific type and define a default value at once.
 * 
 * @param args      Arguments to check. (Required)
 * @param index      Index to check. (Required)
 * @param type      Type to use. (Required)
 * @param default      Value to use if args[index] doesn't exist. Defaults to an empty string if type isn't struct or array. (Optional)
 * @return Returns a value (any type). 
 * @author Jordan Clark (JordanClark@Telus.net) 
 * @version 1, August 20, 2002 
 */
function OptArgType( args, index, type ) {
    if( arrayLen( args ) GTE index AND typeOf( args[ index ] ) IS type ) {
        return args[ index ];
    } else if( arrayLen( arguments ) IS 4 ) {
        return arguments[ 4 ];
    } else {
        switch( type ) {
            case "structure" : return structNew();
            case "array" : return arrayNew( 1 );
            default : return "";
        }
    }
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson