AutoHotkey Tutorial: When to use %, and when not to

If you’re just starting out your bound to run into these problems. Arguably the most confusing part of AutoHotkey is that sometimes you call a variable SomeVariable and others you call it %SomeVariable%. This video tries to draw some rules around it to make remembering easier. Watch it and then read the follow up.

Here are the rules we laid out about when (and when not to) use percentage signs % around variables.

Do use them when…
  • … you are using the = assignment operator
  • … you are using a command. If there is no ( after the action’s name: it’s a command.
    Command: StringGetPos, …
    Function: InStr(…)

Do NOT use them when…

  • … you are using parenthesis, e.g., Func(Var)
  • … You are using the := expression assignment operator
  • … traditional if statements, which you shouldn’t be using anyway, e.g., if Var = literal string value
  • … you are in doubt. It’s easier to notice a MsgBox displaying the name of your variable than a blank MsgBox

There is one more very strange rule: the docs are always right! Get used to looking at the documentation for commands you’re using. You can find all the commands on this page, or go to autohotkey.com, then click Documentation, and choose Command Reference. The part at the top which lists the parameters calls a parameter OutputVar, InputVar, or describes them as variables it expects a variable.

Every built in command is listed there, and I don’t plan to go over all of them so get used to searching. While we’re talking about finding answers, the other really useful tool is a Google SiteSearch of AutoHotkey.com.

Here are some example of correct uses of %s

MyAwesomeVariable := "An awesome string"
MsgBox, %MyAwesomeVariable%

First_Two_Letters := SubStr(MyAwesomeVariable, 1, 2)
Msgbox %First_Two_Letters%

Keep practising! In the next tutorial we learn about the “Auto” in “AutoHotkey.”

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>