0

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! Much simpler than I could imagine. Thanks a lot!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.