tags:

views:

77

answers:

2

How do I call global variables in hotstring functions.

This Works

::hlw:: hlwvar = Hello World sendInput %hlwvar% return

This Doesn't work

hlwvar = Hello World ::hlw:: sendInput %hlwvar% return

A: 

As Chris mentioned the following two codes work exactly the same for me:

::hlw:: 
hlwvar = Hello World 
sendInput %hlwvar% 
return

and

hlwvar = Hello World
::hlw:: 
sendInput %hlwvar% 
return
RaptorX
A: 

I got this answer from "Joel T. 33 / M / Seattle, WA" through Aardvark. I'm posting it here because it was quite useful.

--

Your second form should actually work; try pasting just those 4 lines into a new script and run it to see. Most likely the problem is that in your second example, "hlwvar = Hello World" is not actually being executed because it isn't at the top of the script. When AHK first runs a script, it starts from the top and executes until it encounters a "return" or a hotstring/hotkey definition. Therefore, you should always define your global vars and any other global setup at the top of your script, and once all the script "initialization" stuff is done there, end it with a "return". Then put all your hotstrings/hotkeys/functions below that point.

One thing I like to do is put all my global stuff into a function, e.g. Init() { global someglobalvar = myvalue return } Then at the top of my script I have Init() return

This makes it really easy to identify at a glance where my init stuff lives, as well as move the init routine elsewhere if desired. Note that the "global" keyword must be the first command in a function definition if you want all of the variables assigned inside said function to be available globally.

Eric
Exactly what Chris pointed out and what my answer was about. :)
RaptorX
Except that Chris said "Not sure what the problem is…?" and Joel said "Most likely the problem is that in your second example, "hlwvar = Hello World" is not actually being executed because it isn't at the top of the script." See the difference?
Eric