Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking function with dynamic array of arguments

If I have

<cfset arr_arguments = ["a","b","c"]>
<cfunction name="someFunction">
 <cfargument name="someArgumentOne">
 <cfargument name="someArgumentTwo">
 <cfargument name="someArgumentThree">

</cffunction>

Is there any way to invoke someFunction with the arguments arr_arguments, similar to someFunction("a","b","c")? I of course know I can use argumentCollection to pass a (keyed) structure to a function, but I am specifically asking about passing in an (keyless) array. In JS this could be easily done with someFunction.apply(this,arr_arguments), but in coldfusion I just can't find any way of doing this.

like image 399
David Mulder Avatar asked Jan 14 '23 14:01

David Mulder


1 Answers

Unnamed arguments are passed into a function as a structure with numeric keys matching the positions of the arguments defined in the function arguments. So instead of passing the named arguments, you can convert your array to a struct with numeric keys, and then pass the struct in with argumentCollection:

<cfset arr_arguments = {"1"="a","2"="b","3"="c"}>
<cfset someFunction(argumentCollection=arr_arguments)>

You can easily convert an array to a struct with numeric keys like this:

<cfset args = {}>
<cfloop from="1" to="#arrayLen(arr_arguments)#" index="i">
    <cfset args[i] = arr_arguments[i]>
</cfloop>
like image 123
imthepitts Avatar answered Jan 22 '23 20:01

imthepitts