Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my original array being altered?

Based on Coldfusion documentation... "Arrays are passed to user-defined functions by value, so the function gets a new copy of the array data, and the array in the calling page is unchanged by the function."

So I'm working on a little practice project. I begin by taking a list of numbers, converting it to an array (which I call cardArray), then sorting the array, and finally passing the array to a couple UDFs that will look for various patterns in the numbers, and manipulate (if necessary) the argument (aka the passed array).

I never reference the original array in the UDFs, I only reference the argument name. Still... if I cfdump the original array after calling the functions, my original array has been altered. Can anyone tell me why?

I'm pretty sure I can work around this. Thus fixing this isn't my big problem. My problem is that this behaviour completely contradicts how I "thought" this would work, and it's driving me crazy!

    function hasPair(pairArray) {
        pairCount = 0;
        for (i=2; i lte arrayLen(pairArray); i++){
            if(pairArray[i] is pairArray[i-1]){
                pairCount++
                arrayDeleteAt(pairArray, i)
                arrayDeleteAt(pairArray, i-1)
                i=2
            }
        }
        return pairCount;
    }

    function hasStraight(straightArray){
        sequenceCards = 0;
        for (i=2; i lte arrayLen(straightArray); i++){
            if(straightArray[i] - straightArray[i-1] is 1){
                sequenceCards++
            }
        }
        if (sequenceCards GTE 4){
            return 1;
        }
        else{
            return 0;
        }
    }

</cfscript>

<cfoutput>
    <cfset cardList = "5,6,7,8,10,8,9">
    <cfset cardArray = listToArray(cardList)>
    <cfdump var="#cardArray#" label="Original Array Before">
    <cfset arraySort(cardArray, "numeric", "desc")>
     #hasPair(cardArray)# <br/> 
     #hasStraight(cardArray)# <br/> 
    <cfdump var="#cardArray#" label="Original Array After">
</cfoutput>

Results in:

Original array BEFORE function call [6,6,7,8,10,8,9].

Original array AFTER function call [10,9,7,6,5]

The array is sorted (which I expect, and is correct). However, the 8s are also missing. I did NOT expect this. The 8s are removed by the arrayDeleteAt(pairArray, i) and arrayDeleteAt(pairArray, i-1) methods in the first function. BUT this should be removing elements only from the array argument (pairArray), not the original array (or so I thought).

like image 329
mts1701 Avatar asked Jan 06 '23 12:01

mts1701


1 Answers

Since you have Lucee tagged here, I'm assuming you are running this on Lucee and not Adobe's implementation. Lucee does not conform to the Adobe spec in this case; arrays are passed by reference like all other complex objects.

like image 130
Tim Jasko Avatar answered Jan 15 '23 01:01

Tim Jasko