Friday, 24 September, 2004

Well I learnt something new about ASP yesterday. It's actually something really elementary that's avoided my discovery for the last couple of years. It's a lesson about scope.

Examine the following script:

<%

function Test()
a=a+1
b=1
end function

a=1

Test()

Response.write "Value of A:" & a & "<br />"
Response.Write "Value of B:" & b & "<br />"

%>

If you comment out Test() on line eleven then the value of 'a' is one and the value of 'b' is null. If you leave the Test() line in the script then the value of 'a' is two but the value of 'b' is still null. What's going on here?

Well the variable 'a' is set to one on line twelve. This initialises the variable 'a' as a global variable in the script. Every sub or function in the script can then see this variable and adjust it. When Test() is executed it increments the global variable 'a' by one. This results in the value of 'a' being printed as two. Because the variable 'b' is only initialised in the Test function and not in the main script the variable 'b' is only scoped to that function. This is why when the value of 'b' is printed on line fourteen it shows it as containing nothing.

Like I said, a pretty basic lesson but I really wonder how many ASP programmers know about this particular feature of the language?

Simon

13:15:23 GMT | #Programming | Permalink
XML View Previous Posts