Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

In a classic ASP function, when I do a loop inside another as shown in the code below I have a stack overflow error.

Function shift(x,y)
    shift = x
    For i = 1 to y
    shift = shift*2
Next
End Function

Function translate_url(iVal)
sAlpha = "abcdefghijklmnopqrstuvwxyz-_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
doWrite = False
iBase = 63 'DO NOT CHANGE
For i = 4 to 0 step -1
    iPos = (iVal and shift(iBase, i*6))/shift(1, i*6)
    If iPos Then doWrite = True
    If doWrite Then translate_url = translate_url & Mid(sAlpha, iPos + 1,1)
Next
End Function

arr = Split("1,2,3,4,5,6,7,8,9,0",",")

For Each i In arr
response.Write(translate_url(arr(i)))
next

The error does not occur when I remove the loop outside the function. Eg:

response.Write(translate_url(arr(1)))

return "c".

What I need to do to make the code flows down the array and return the corresponding values ​​according to the function?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

VBScript has a dark side. Variables scope is one of them.

When you don't declare a variable, VBScript will do it for you, free of charge or error and give it global scope.

What does it mean? Take a look in the main loop:

For Each i In arr
    response.Write(translate_url(arr(i)))
next

The i variable becomes global. When you have this later in the function:

For i = 4 to 0 step -1
    '...
Next

It's changing the same i variable. This is causing endless loop of function calls.

To resolve this, declare i locally in each function:

Function shift(x,y)
    Dim i
    '...
End Function

Function translate_url(iVal)
    Dim i
    '...
End Function

And it will be different variable and no overflow.

share|improve this answer
2  
Brilliant! Much simpler than I could imagine. Thanks a lot! – afazolo Jun 12 '13 at 12:22

As the EVIL global variable i is used in your top level loop and in the functions shift() and translate_url(), you got what you deserve.

Evidence: Just change your loop to

For Each NoliMeTangere In arr
  response.Write translate_url(arr(NoliMeTangere))
next

Remedy: Use "Option Explicit" and Dim all local variables in your Subs/Functions/Methods.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.