3

Sorry, this is the best title I can come up with.

I am hoping someone on here can give me an explanation to this behavior. My employer just decided to upgrade CF 8 to CF 10 (yeah, I know). However, some of the servers are on CF 10 and some are on CF 8. I know it is not supposed to be like this; but this is not within my control. Anyway, I have the following codes. It breaks in CF 8 but works in CF 10 without errors. In CF 8, it is saying that element a is not defined in local, which is expected and I don't have a problem with that. After all, local is declared twice and a is not defined in the second one.

But in CF 10, no errors generated and local.a is returned by the function. To me, CF 10 should throw an error either because the same reason why CF 8 fails or because "local" is a reserved word in CF 10 ("local" was introduced in CF 9). Why is it that CF 10 does not throw any errors?

<cfcomponent name="myComponent">
<cffunction name="myFunction" returntype="Numeric">
<cfscript>
var local = StructNew();
local.a = 1;
</cfscript>

<cfset local = StructNew()>

<cfif local.a is 0>
<!--- do something --->
</cfif>

<cfreturn local.a>
</cffunction>
</cfcomponent>
Monte Chan
  • 1,193
  • 4
  • 20
  • 42
  • 1
    I agree that CF 10 should throw an error, but I think it should throw a different error. I think it would throw an error at the variable being created. ColdFusion 9 introduced the `local` scope and I _think_ what is happening is that a variable named 'local' is actually being created, but, when you try to set `local.a`, it is being set in the `local` scope rather than the variable named `local`. So `local.a` actually does exist, but it is in the `local` scope rather than the variable named `local`. Make sense? – Scott Stroz Dec 13 '13 at 12:51
  • Also note that the second time you set `local` there is no `var` so the variable will not be local to the function. – Scott Stroz Dec 13 '13 at 12:52
  • 2
    As I understand it, once you have var'd a variable once, it's local to the function no matter how many times it changes it's value. – Dan Bracuk Dec 13 '13 at 13:06

1 Answers1

6

Somewhat in defiance of what any sane person would think is common sense, ColdFusion 9 (and accordingly 10) has been hard-coded to ignore this statement:

local = structNew();

Or:

local = {};

This is to provide "backwards compat" with people who have traditionally used local as a pseudo local scope in older versions of CF.

Adobe did this on purpose, believe it or not.

You can demonstrate this by running this code on cflive.net:

function f(){
    var local = {};

    local.a = "set at top";

    local = {};

    writeDump(var=local);
}

f();

Railo, bless 'em, have followed ColdFusion's lead here, for the sake of cross-compatibility.

Adobe did a very daft thing here, and now we're stuck with it. But that's why you're seeing what you're seeing.

Adam Cameron
  • 29,677
  • 4
  • 37
  • 78