Still confused about when to use % with variables? This helped me figure it out

Helpful script writing tricks and HowTo's
SAbboushi
Posts: 252
Joined: 08 Dec 2014, 22:13

Still confused about when to use % with variables? This helped me figure it out

Post by SAbboushi » 09 May 2018, 11:09

Despite the excellent and comprehensive AHK documentation and support forum, I've had some difficulty getting crystal clear on when I need to use the "% space prefix" vs. just the variable name vs. surrounding the variables in %

I wrote this script to help me figure it out and am posting in case it can help others too.

Code: Select all

; Variables and percent signs.ahk
; See https://autohotkey.com/docs/Language.htm#expressions-vs-legacy-syntax

; See bottom of script for usage in commands e.g. IfWinExist

; my favorite "gotcha":  if (z3 = "") (see below)

#NoEnv
#SingleInstance Force ; prevents multiple instances of script from running


; AHK supports "unquoted text"
w = y ; value of w is the literal/text string "y"
v := w ; value of v is the literal/text string "y"

w2 =  2  ; Note whitespace around the "2"
w3 := 2
if (w2 = w3) 
	MsgBox Yes ; seems whitespace is ignored
	
MsgBox % """" . w2 . """" ; just confirming: there are 2 spaces before and after "2" (i.e. "w2 =  2  ") but it looks like such whitespace is ignored
	
MsgBox, Yes ; treats "Yes" as unquoted text
MsgBox, % Yes ; treats "Yes" as variable name "Yes" (which is unassigned/empty)
MsgBox, % "Yes" 

if x = y ; legacy/"traditional" if statement and unquoted text "y"
{
	sleep , 1
}
else
{
	sleep , 1 ; this line executes because x is treated as a variable and y as a literal. x is uninitialized.  AHK HAS NO VALUE FOR NULL.  UNINITIALIZED VARIABLES ARE EMPTY/BLANK STRINGS i.e. length of 0
}

if (x = y) 	; if (expression) DOES NOT SUPPORT UNQUOTED TEXT: x and y are treated as variables
{
	sleep , 1 ; this line executes because x and y are uninitialized/empty and thus equal
}
else
{
	sleep , 1
}

; Don't need braces if only 1 statement/command per if or else statement
if (x = y) ; if (expression)
	sleep , 1 ; this line executes because x and y variables are both uninitialized/blank and thus equal
else
	sleep , 1 


if z = 
{
	sleep , 1 ; this line executes because variable z has not been initialized and I guess therefore matches blank/empty
}
else
{
	sleep , 1
}


; z1 has not been initialized
if z1 = ""
{
	sleep , 1 
}
else
{
	sleep , 1 ; gotcha? this line executes because variable z1 has not been initialized and doesn't equal the literal consisting of two doublequotes
}

if (z2 = "")
{
	sleep , 1 ; this line executes because variable z2 has not been initialized and is blank/empty; since the expression is within parentheses, the pair of doublequotes is interpreted as a blank/empty literal
}
else
{
	sleep , 1
}

z3 = ""
if (z3 = "")
{
	sleep , 1
}
else
{
	sleep , 1 ; gotcha? this line executes because the value of z3 is a literal string (i.e. a pair of doublequotes) whereas the expression (z3 = "") is testing whether z3 is empty (i.e. has a string length of 0); an expression interprets a pair of doublequotes as a blank/empty literal
}




a1 = 1 + 2 ; assigns the literal "1 + 2"

a2 := 1 + 2 ; assigns 3 because of assignment operator ":=" and the valid math expression

a3 = ( 1 + 2 ) ; assigns the literal "( 1 + 2 )"

a4 := ( 1 + 2 ) ; assigns 3 because of operator ":=" and the valid math expression

a5 := a1 ; assigns the literal "1 + 2"

a6 := a1 + a3 ; assigns empty because of assignment operator ":=" and invalid math expression (adding together two literal text strings)

a7:= a1 + a2 ; assigns empty because of assignment operator ":=" and invalid math expression (adding together a literal text string (value of a1 is "1 + 2") and a number (value of a2 is 3))



b1 = a1 ; assigns literal "a1"

b2 = %a1% ; assigns literal "1 + 2"

b3 := a1 ; assigns literal "1 + 2"

b5 := %b1% ; assigns the literal "1 + 2"

; b4 := %a1% ; results in a terminal error "the following variable name contains an illegal character: '1 + 2'"; the percent signs identify the contents (i.e. value) of variable a1 as the name of a variable, that variable name being "1 + 2", which is an illegal variable name


MsgBox The value in the variable named b3 is %b3%. ; unquoted text
MsgBox % "The value in the variable named b3 is " . b3 . "." ; displays same as line above

MsgBox The value in the variable named b3 is """"%b3%"""". ; unquoted text, displays 4 doublequotes
MsgBox % "The value in the variable named b3 is " . """" . b3 . """" . "." ; need 4 doublequotes to display 1 when using quoted text



; EACH PARAMETER that has variables needs to be preceded with % space prefix:
FileRead, GetLastVersePageFile, % QIEpath Title ".txt" ; QIEpath and Title are variables


; EXAMPLE with multiple parameters:

WinTitle := "SciTE.exe" ; J:\StandaloneApps\AutoHotkey\SciTE\SciTE.exe
WinText := "Source"
ExcludeTitle := "xxyyzz"

; IfWinExist [, WinTitle, WinText, ExcludeTitle, ExcludeText] (deprecated, but using it as example of a command that uses traditional (i.e. non-expression) syntax which requires understanding of how/when to use "% space prefix" vs. just the variable name vs. surrounding the variables in %):
IfWinExist, ahk_exe %WinTitle%, % WinText, % ExcludeTitle ; each parameter syntax is separate, so I can use unquoted/legacy syntax for one parameter (i.e. ahk_exe %WinTitle%) and expression syntax with the other parameters
	MsgBox, Yes!

IfWinExist, % "ahk_exe " . WinTitle, % WinText, % ExcludeTitle ; Using expression syntax for all parameters
	MsgBox, Yes!

User avatar
Era
Posts: 26
Joined: 28 Apr 2018, 22:36

Re: Still confused about when to use % with variables? This helped me figure it out

Post by Era » 16 May 2018, 18:35

You and most of us. What's the use of those differently punctuated variable names? Makes no sense to me

User avatar
Cerberus
Posts: 172
Joined: 12 Jan 2016, 15:46

Re: Still confused about when to use % with variables? This helped me figure it out

Post by Cerberus » 29 May 2018, 18:20

Excellent for beginners! This is indeed among the most confusing inconsistencies in Autohotkey. I think the best solution is a good syntax highlighter: if you consistently highlight strings or string content as, say, yellow; special symbols that are active/working as purple (e.g. percentage signs in the right context); and the rest as white, like variable names; then it's easy for the user to get it right. The problem is that it is quite a complex task to write a proper syntax highlighter to apply these rules, because you need to classify each parameter in each command/function/operation.

icuurd12b42
Posts: 202
Joined: 14 Aug 2016, 04:08

Re: Still confused about when to use % with variables? This helped me figure it out

Post by icuurd12b42 » 29 May 2018, 21:28

I reduced this to 2 rules

1) always use variable :=
2) always use %variable% to extract the content of the variable for commands that require it

Name := "John"
MsgBox, Hello %Name%, How are you today.

That's it! nothing complicated, nothing convoluting, nothing confusing. just obey these 2 rules and that will normalize your coding to a proper standard and reduce issues to basically one recurring issue which will be, Ooops I used = instead of :=, which you will instantly spot when something fishy happens.

I never use the % in any other situation than when having to use a command...

Even for text concatenation I use the . operator, because that is what I would do in 99.9999% of all programing language, though it would likely be the + operator...

Sentence := "Hello " . Name . ", How are you today."
MsgBox, %Sentence%

User avatar
nnnik
Posts: 4500
Joined: 30 Sep 2013, 01:01
Location: Germany

Re: Still confused about when to use % with variables? This helped me figure it out

Post by nnnik » 29 May 2018, 23:56

I simply use a single % in commands to make them expression mode command.
Recommends AHK Studio

User avatar
jackdunning
Posts: 126
Joined: 01 Aug 2016, 18:17
Contact:

Re: Still confused about when to use % with variables? This helped me figure it out

Post by jackdunning » 21 Aug 2018, 06:37

There are excellent reasons for occasionally forcing expressions with the % operator. The blog "Force an Expression (%) in AutoHotkey for More Powerful Commands" offers a beginner's explanation.

Also, for a better understanding of %var% replacement, check out the "" section of Variable Evaluation (% Var) Versus Variable Text Replacement (%Var%)."

Skrell
Posts: 302
Joined: 23 Jan 2014, 12:05

Re: Still confused about when to use % with variables? This helped me figure it out

Post by Skrell » 06 Jul 2022, 13:51

I find this issue gets compounded by tnfthe fact that somefunctios take in string titles and some take in titles as variables. In other words, how do I know that a built in function wants something like (" valu " .e%var )hk_i(d %valuevarI)t seems like the built in functions vary bbetwen these 2 methodologies ccorret?

guest3456
Posts: 3453
Joined: 09 Oct 2013, 10:31

Re: Still confused about when to use % with variables? This helped me figure it out

Post by guest3456 » 06 Jul 2022, 21:41

Skrell wrote:
06 Jul 2022, 13:51
I find this issue gets compounded by tnfthe fact that somefunctios take in string titles and some take in titles as variables. In other words, how do I know that a built in function wants something like (" valu " .e%var )hk_i(d %valuevarI)t seems like the built in functions vary bbetwen these 2 methodologies ccorret?
its pretty simple, FUNCTIONS always take the expression syntax (quotes around strings, and no % for vars)

COMMANDS almost always take the literal syntax (no quotes for strings, and usage of %var%)


Skrell
Posts: 302
Joined: 23 Jan 2014, 12:05

Re: Still confused about when to use % with variables? This helped me figure it out

Post by Skrell » 07 Jul 2022, 09:51

guest3456 wrote:
06 Jul 2022, 21:41
Skrell wrote:
06 Jul 2022, 13:51
I find this issue gets compounded by tnfthe fact that somefunctios take in string titles and some take in titles as variables. In other words, how do I know that a built in function wants something like (" valu " .e%var )hk_i(d %valuevarI)t seems like the built in functions vary bbetwen these 2 methodologies ccorret?
its pretty simple, FUNCTIONS always take the expression syntax (quotes around strings, and no % for vars)

COMMANDS almost always take the literal syntax (no quotes for strings, and usage of %var%)
Thank you for confirming what I suspected! Also thank you for reading through my garbled mess! (don't know what happened there!)

Post Reply

Return to “Tutorials (v1)”