Trying to add variable outside the hotkey's loop

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
southpaw26
Posts: 13
Joined: 29 Nov 2021, 16:31

Trying to add variable outside the hotkey's loop

Post by southpaw26 » 29 Nov 2021, 17:01

I want to write a program where z is printed 50 times when i press a key and increments by 50 each time i press the same key again. When i tried i was not able to initialize the variable outside the hotkey.

Code: Select all


i=1 
#a::
loop, i
	{
	send {z 50}
	}
i+=1


User avatar
mikeyww
Posts: 26437
Joined: 09 Sep 2014, 18:38

Re: Trying to add variable outside the hotkey's loop

Post by mikeyww » 29 Nov 2021, 17:23

Welcome to AHK!

Code: Select all

#a::SendInput % "{z " (i := i ? i + 50 : 50) "}"
Demonstration:

Code: Select all

i = 2
#a::
Loop, i
 Send x
Loop, %i%
 Send y
Return
Due to the need to support file-pattern loops, Count cannot be an expression. However, as with all non-expression parameters, an expression can be forcibly used by preceding it with a % and a space. For example: Loop % Count + 1. In such cases, the expression is evaluated only once, right before the loop begins.

southpaw26
Posts: 13
Joined: 29 Nov 2021, 16:31

Re: Trying to add variable outside the hotkey's loop

Post by southpaw26 » 29 Nov 2021, 18:02

Thanks! But I am still not able to increment when i press the key for the second time. What am I doing wrong?

i = 1 ;

Code: Select all

#a::
loop, %i%
{
send {z 50}
}
i = i + 1;
return

User avatar
mikeyww
Posts: 26437
Joined: 09 Sep 2014, 18:38

Re: Trying to add variable outside the hotkey's loop

Post by mikeyww » 29 Nov 2021, 18:11

If your variable is null, your loop will do nothing. Would try the script that I posted. You can report whether it works or does not work.

Use := to evaluate expressions.

If you are not sure what the value is, you can use MsgBox to display it.

southpaw26
Posts: 13
Joined: 29 Nov 2021, 16:31

Re: Trying to add variable outside the hotkey's loop

Post by southpaw26 » 29 Nov 2021, 18:21

The code you sent does work but I didn't understand the logic behind it. Is there any simpler way to write it?

User avatar
mikeyww
Posts: 26437
Joined: 09 Sep 2014, 18:38

Re: Trying to add variable outside the hotkey's loop

Post by mikeyww » 29 Nov 2021, 18:37

Code: Select all

i = 0
#a::
i := i + 1
Loop, %i%
 SendInput {z 50}
Return

southpaw26
Posts: 13
Joined: 29 Nov 2021, 16:31

Re: Trying to add variable outside the hotkey's loop

Post by southpaw26 » 30 Nov 2021, 05:28

It worked! Thanks a lot for your help! :)

Post Reply

Return to “Ask for Help (v1)”