fwinans
fwinans

Reputation: 45

autohotkey assign a text expression to a variable

In an autohotkey script I was trying to assign a text string to a variable. Can anyone spot why this doesn't work, it looks just like some provided examples? I don't need the variable anymore, but now I'm just curious what I did wrong...

myvar := % "foo" ; creates global variable myvar, but has no contents

I know you could just say myvar = foo but leaving quotes off a fixed text string just makes me cringe. I even had it working but didnt' save my file before making 'a few harmless cosmetic edits.' I click on the "H" task icon near the clock, use menu File / show variables to verify the empty contents...

Upvotes: 3

Views: 6702

Answers (1)

bgmCoder
bgmCoder

Reputation: 6371

Okay, so we assign a value to a variable:

eval_this:= "harry"

If you do it this way, you just read the contents of the variable:

msgbox %eval_this%   ;=harry

Of course, here, the text is not evaluated - "eval_this" is just text to ahk:

msgbox eval_this     ;= eval_this

This method is called a "Forced Expression" - which is what you are looking to do. It tries to read the text string as if it were code. It isn't reading the contents of any variable, it is looking at the text and forcing it to become a variable (it's sort of the same thing, but not really)

msgbox % eval_this   ;= harry

This also gets us harry, and you can see how we are reading the variable:

test := eval_this    
msgbox %test%        ;=harry

Same thing, different approach (forcing the text to become a variable):

test = % eval_this
msgbox %test%        ;=harry

Consider this, where we force both text strings into their actual values

eval_this := "harry"
this_too := " and bob"

test = % eval_this this_too
msgbox %test%               ;= harry and bob

Okay, now that you've got all that, here is a practical application. We will force the value of the text string to be a variable. Since we've actually defined what "alert" is, then the gosub will call that definition. Pop this into a script and run it:

eval_this := "alert"

gosub % eval_this
exit  ;we are finished with the demo, so end here

alert:
    msgbox harry
return

Upvotes: 4

Related Questions