Jump to content


Photo

Funtion and Variable


  • Please log in to reply
3 replies to this topic

#1 shyangs

shyangs
  • Members
  • 6 posts

Posted 19 July 2012 - 11:50 AM

;Ex1
outside := 111
function()
{
  x := outside
  MsgBox, % x
}
function()
;Ex2
outside := 111
function()
{
  x := "outside"
  x := %x%
  MsgBox, % x
}
function()

I can figure out the result of Ex1. But why the result of Ex2 is 111? I expect it same as Ex1.

#2 Guests

  • Guests

Posted 19 July 2012 - 11:58 AM

See <!-- m -->http://www.autohotke...ions.htm#Locals<!-- m --> about local and global variables, better to pass it on as in function3 shown here
outside := 111



Function1()

Function2()

Function3(outside)



function1()

{

	global

  x := outside

  MsgBox, % "func1: " x

}



function2()

{

	x := "outside"

  x := %x% ; you are dereferencing a variable

  MsgBox, % "func2: " x

}



function3(x)

{

  MsgBox, % "func3: " x

}


#3 shyangs

shyangs
  • Members
  • 6 posts

Posted 19 July 2012 - 12:22 PM

What I interest is not which is the better way.

I think the result of Ex2 should be blank, because x be dereferenced, which will result in the string "outside". Then, the value of the variable "outside" (which currently has no value, I have not assigned any value in function) will be assigned to "x". Therefore, "x" will be blank. Actually, it is 111. I want to know the reason.

#4 Guests

  • Guests

Posted 19 July 2012 - 01:20 PM

Any non-dynamic reference to a variable creates that variable the moment the script launches. For example, when used outside a function, MsgBox %Array1% creates Array1 as a global the moment the script launches. Conversely, when used inside a function MsgBox %Array1% creates Array1 as one of the function's locals the moment the script launches (unless assume-global is in effect), even if Array and Array0 are declared global.
Source: http://www.autohotke...s/Functions.htm