Sign in to follow this  
Followers 0
JoeCool

Local variable strange behavior ...

3 posts in this topic

#1 ·  Posted (edited)

EDIT:

Well it's not a bug... I should read the manual ;-)

func vectDisplay( $v, $title )
    dim $i, $str = ""

    for $i = 0 To ubound( $v ) - 1
        $str &= "[" & $i & "] = " & stringStripCR( $v[$i]  ) & @CR
    next
    msgbox( 4096, $title, $str )
endfunc


func vectNew( $p )
; work find with
;local dim $v[1]
   dim $v[1]
   dim $i

   if $p > 0 then
      redim $v[ $p ]
      for $i = 0 to $p - 1
         $v[$i] = $i
      next
   endif
    return( $v )
endfunc

;---------

dim $v , $v2

$v = vectNew( 5 )
vectDisplay( $v, "v new" )

$v2 = vectNew( 10 )
vectDisplay( $v, "v start" )
vectDisplay( $v2, "v2 start" )

Strange behavior ... My variables got zapped!

$v got zapped after second call to vectNew().

It seems than local variable defined with dim have some problem, isn't it suppose to be local ?

:evil:

I'm in the dark :)

Edited by JoeCool

Share this post


Link to post
Share on other sites



This one got me too, and I didn't figure it out until just recently:

It seems that $dim in a function will create a local variable, but only if a variable of that name doesn't already exist in the global scope. If a variable exists in the global scope and you dim it in a function, the global variable is destroyed.

So it's a good habit to get in to to always make your local variable local.

I don't let myself use dim anymore, I force myself to use either local or global. You should only use dim when you plan to effect a global variable from within a function, which is generally bad style anyway.

Share this post


Link to post
Share on other sites

This one got me too, and I didn't figure it out until just recently:

It seems that $dim in a function will create a local variable, but only if a variable of that name doesn't already exist in the global scope.  If a variable exists in the global scope and you dim it in a function, the global variable is destroyed.

So it's a good habit to get in to to always make your local variable local.

I don't let myself use dim anymore, I force myself to use either local or global.  You should only use dim when you plan to effect a global variable from within a function, which is generally bad style anyway.

<{POST_SNAPBACK}>

Ohlala ! ( I was reading the help file too ... )

I never thought about someting weird like that ....

I thought dim was the same has local inside a variable and global for static variable inside the script ...

Well I'll have to rewrite some code then ...

Is it the same behavior for Vbasic ?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0