autohotkey assign a text expression to a variable

两盒软妹~` 提交于 2019-12-08 01:01:40

问题


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...


回答1:


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


来源:https://stackoverflow.com/questions/17498589/autohotkey-assign-a-text-expression-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!