Mar 01
var scoped variables uncovered
Posted by James Netherton | Thursday 01 March 2007 9:58 PM | In ColdFusion
I was messing around with some of the ColdFusion coldfusion.runtime.NeoPageContext methods which can be utilised via the getPageContext() method.
One of the methods is getActiveFunctionLocalScope(), which, as it's name suggests, returns the active locally scoped variables within a CF function.
For example:
<cffunction name="test" returntype="void">
<cfset var a = "I'm a"/>
<cfset var b = "I'm b"/>
<cfset var c = "I'm c"/>
<cfset localScope = getPageContext().getActiveFunctionLocalScope()/>
<cfdump var="#localScope#">
</cffunction>
<cfset test()/>
<cfset var a = "I'm a"/>
<cfset var b = "I'm b"/>
<cfset var c = "I'm c"/>
<cfset localScope = getPageContext().getActiveFunctionLocalScope()/>
<cfdump var="#localScope#">
</cffunction>
<cfset test()/>
Produces the output:

What would be cool is if you could add variables to the local scope on-the-fly without declaring them. It must be possible so I'll have a look at some of the other methods.
2 Comments
[Post comment]
1
Posted by dis | Monday 27 August 2007 10:39 AM
Does adding:
<cfset Structinsert(localscope,"d","I'm d",false) />
<cfdump var="#getPageContext().getActiveFunctionLocalScope()#" />
As the last two lines of the function accomplish what you meant?
2
Posted by James Netherton | Monday 27 August 2007 11:27 AM
Good call! Thanks for pointing that out as it never crossed my mind to try that at the time I wrote this post.
I didn't think it would work, but if you do:
<cfdump var="#d#"/>
It prints out it's correct value which is 'false'. So it does seem to be working. The real test would be to call the function recursively and if nothing unexpected happens to the value of the variable, we can be pretty sure it has been given local function scope.