Code Cleaning

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
hBoom
Posts: 1
Joined: 16 Jun 2021, 22:50

Code Cleaning

Post by hBoom » 16 Jun 2021, 23:35

I'm new to AHK (started 1 hour ago). I have some Python language experience.
I put this script together from searching through the forums and the documentation.
I just wanted to ask what I can do to clean up my coding in AHK.
The "doesn't work reliably" comment near the bottom refers to the toggling off after activating the loop.

Code: Select all

; Delays "x"ms with added randomness
randDelay(x)
{
  Random, rand, 0, 4000
  rand := Sqrt(rand)*10
  rand := round(rand)
  sleep x + rand
}

; Presses key with random press time (avg. time 130ms)
randKey(x)
{
  Random, rand, 0, 40000
  rand := Round(Sqrt(%rand%)/10)

  SendInput {%x% down}

  Random, plus, 0, 1
  if (plus = 0)
  {
    rand := -%rand%
  }

  Sleep 130 + rand

  SendInput {%x% up}
}

; Presses mouse button (copy pasted code) with random press time (avge. time 110ms)
randClick()
{
  Random, rand, 0, 40000
  rand := Round(Sqrt(%rand%)/10)

  Send {LButton down}

  Random, plus, 0, 1
  if (plus = 0)
  {
    rand := -%rand%
  }

  Sleep 110 + rand

  SendInput {LButton up}
}

; Main Program
#MaxThreadsPerHotkey 2

; Looped code toggles with pressed keybind Alt+\ (doesn't work reliably for whatever reason)
!\::
{
  Toggle:=!Toggle
  While, Toggle
  {
    randClick()
    randDelay(1500)
    randKey(1)
    randDelay(23500)
  }
}
Last edited by hBoom on 17 Jun 2021, 00:03, edited 2 times in total.
User avatar
Hellbent
Posts: 2102
Joined: 23 Sep 2017, 13:34

Re: Code Cleaning

Post by Hellbent » 17 Jun 2021, 01:32

It looks like you should be able to fix this by using

#MaxThreadsPerHotkey

Code: Select all

;Put this at the top of your script
#MaxThreadsPerHotkey, 20 ;Because you have a fairly long sleep time you will want to use a number higher than 2 so you don't end up with both stuck in your loop. 20 should be more than enough. Or you can just max it out at 255.



;*Edit* To be clear. You can keep this where you had it, only the #Max... goes at the top
; Looped code toggles with pressed keybind Alt+\ (doesn't work reliably for whatever reason)
!\::
{
  Toggle:=!Toggle
  While, Toggle
  {
    randClick()
    randDelay(1500)
    randKey(1)
    randDelay(23500)
  }
}
Post Reply

Return to “Ask for Help (v1)”