Calling code automatically

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
MindCaged
Posts: 19
Joined: 19 Jun 2014, 12:33

Calling code automatically

19 Jun 2014, 23:09

Yeah, I'm wondering if there's any better way of doing this. I don't like to have to scroll to the top of my script to put all the startup code for the different parts at the top of my script in the autoexec section. Right now I have a bit of code that calls labels with an incremental number. Like ProgInit1: ProgInit2: ProgInit3:.

This works but has its limitations, for one thing as I go back and forth in the script adding code the labels get out of order over time which isn't really a problem but it urks me a little. I also have code that lets me know the next free number to use for new labels so remembering which numbers are free isn't too much of a problem.

I suppose I could have the script open itself and scan line by line looking for a certain pattern of labels, but that only works for uncompiled, which I suppose is alright since I'll probably never compile this particular file since I'm always adding stuff and making changes, but I also don't care for the idea. Also, I'd have to account for #Includes and such, so it wouldn't be easy.

Does anybody have any other ideas? I have a thought for another way which might avoid the drawbacks of both, with only a minor drawback which isn't really much of one, but I want to know if anybody else has any ideas I haven't thought of.
kon
Posts: 1756
Joined: 29 Sep 2013, 17:11

Re: Calling code automatically

19 Jun 2014, 23:23

You could use functions with static variables.

Quick Edit: Here's an example of a function with two static variables. The line static n1 := 1, n2 := Init_n2() is executed once when the script first loads to give the variables their initial values. The initial declarations can even call other functions, ie Init_n2().

Code: Select all

Sleep, 2000
Loop, 5
	MsgBox, % MyFunction()
return

MyFunction() {
	static n1 := 1, n2 := Init_n2()
	n1++
	n2++
	return n1 "`n" n2
}

Init_n2() {
	MsgBox, Init_n2() is running...
	Random, n2, 1, 10
	return n2
}
MindCaged
Posts: 19
Joined: 19 Jun 2014, 12:33

Re: Calling code automatically

20 Jun 2014, 00:06

Dang, I thought I was so brilliant coming up with that on my own. In my case I made a function to compile a list of initialization functions to run, and then run them toward the end of the autoexec section. The register function only registered their own function. In this way they can register themselves at any point in the code. It is a little annoying to have to add that static declaration in every function, but I guess there's just no other ways that I haven't already listed. Unless somebody else has thought of something. I suppose I could add a hotstring to add the declaration easier.

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: dipahk, Google [Bot] and 241 guests