Using Array-Like Structs As Arrays In Lucee CFML 5.3.7.47
The other day, when I was working on unifying type casting errors in Lucee CFML, I spent some time digging around in the Lucee source code on GitHub looking for examples of casting error messages. As I was doing this, I came across a Java class called StructAsArray
. This wrapper class appears to allow array-like Structs to be treated as Arrays in some scenarios. I don't recall ever seeing this discussed; so, I wanted to perform a quick experiment in Lucee CFML 5.3.7.47.
Based on the code that I am seeing in the Java class, it looks like this "Arrayish" wrapper depends on the keys in the Struct being composed entirely of integer values. This makes sense since - depending on how hard you squint - an Array can be thought of as a Struct that associates numeric indices with values (and has a predictable iteration sequence).
That said, let's try to create a Struct with numeric keys and see what happens:
<cfscript>
arrayish = {
1: "First Value",
2: "Second Value",
3: "Third Value"
// NOTE: Array-like structures with a "sparse" distribution of keys don't really
// work the way they would with a true array. It seems they should be avoided.
// --
// 10: "Sparse Value"
};
// NOTE: Member-methods don't work consistently (since this is actually a Struct). As
// such, BIFs (built-in functions) are safest for array-like structures.
echo( "Length: #arrayLen( arrayish )# <br />" );
echo( "First: #arrayFirst( arrayish )# <br />" );
echo( "Last: #arrayLast( arrayish )# <br />" );
echo( "<br />" );
// Try looping using array-iteration.
loop
index = "i"
value = "value"
array = arrayish
{
echo( "#i# : #value# <br />" );
}
arrayDeleteAt( arrayish, 1 );
arrayPrepend( arrayish, "Prepended value" );
arrayAppend( arrayish, "Appeneded value" );
echo( "<br />" );
dump( arrayish );
</cfscript>
As you can see, our Struct variable, arrayish
, is just a normal Struct that happens to have keys that look like array indices. Of course, the object is still a Struct, which means that the member methods are all "struct" member methods. As such, we have to use the Built-In Functions (BIFs) for Arrays in to get this wrapper behavior for Structs to work.
That said, when we run the above code, we get the following output:
As you can see, since our Struct looks like an Array, we can treat it like an array in a subset of Array use-cases.
To be honest, I don't have an immediate use-case for this. It was just a curiosity. I assume this is something that Lucee CFML is using internally? Does anyone have a good example of where something like this might be helpful?
Want to use code from this post? Check out the license.
Reader Comments
@All,
I wonder now if it would make sense for ColdFusion to just have an
arrayFrom()
built-in function:www.bennadel.com/blog/4258-for-consideration-an-arrayfrom-function-in-coldfusion.htm
... something that could take array-like and other iterable values and turn them into native ColdFusion arrays.