Skip to main content
Participant
September 24, 2010
Answered

CF 8.0 cfscript variable

  • September 24, 2010
  • 2 replies
  • 795 views

Pls check if this is a bug cos it seemed like the cfscript and main cfoutput shared the same variable:

Result : 5

Expeced Result: 1

<cfscript>

function

valid4D(str)

{

if (len(str) neq 4)

return false;

if (Ucase(str) eq "XXXX")

return false;

for(i = 1; i lte 4; i = i + 1){

c =

Mid(str, i, 1);

if (Not Find(c, "0123456789xX"))

return false;

}

return true;

}

</cfscript>

<cfloop

from="1" to="1" index="i">

<cfif not #valid4D("5555")#>

<cfset err= 1>

</cfif>

<cfoutput>#i#</cfoutput>

</cfloop>

    This topic has been closed for replies.
    Correct answer -__cfSearching__-

    it seemed like the cfscript

    and main cfoutput shared the same variable:

    That is entirely possible. It does not look like you are VAR scoping your function variables. So when you declare your variables inside the function they are placed in the shared "variables" scope. The "variables" scope is accessible to the whole page, including your "main cfoutput".

    You need to VAR scope all of your function local variables so they do not leak into the shared "variables" scope.

    function valid4D(str){

    VAR i = "";

    VAR c = "";

    .... etc ....

    }

    2 replies

    Inspiring
    September 24, 2010

    cfSearching probably gave you the right answer.  This response concerns troubleshooting techniques. 

    Keep them as simple as possible.  Yours is horribly convoluted with unnecessary loops and the use of double negatives.  If you want to check your function, do this:

    <cfdump var "#valid4D(5555')#">

    If you don't get the expected result, start using writeoutputs inside your function so you can see at what point it deviates from your expectations.

    -__cfSearching__-Correct answer
    Inspiring
    September 24, 2010

    it seemed like the cfscript

    and main cfoutput shared the same variable:

    That is entirely possible. It does not look like you are VAR scoping your function variables. So when you declare your variables inside the function they are placed in the shared "variables" scope. The "variables" scope is accessible to the whole page, including your "main cfoutput".

    You need to VAR scope all of your function local variables so they do not leak into the shared "variables" scope.

    function valid4D(str){

    VAR i = "";

    VAR c = "";

    .... etc ....

    }