Page 1 of 1

initialization in a library

Posted: 21 Sep 2022, 07:17
by Micromegas
When a library is called, how can one ensure that the variables common to the library get initialized?

Example:
When the following script (callee.ahk)

Code: Select all

global x
global y
callee_set(1,2)

callee_set(x_new, y_new) {
	x:= x_new
	y:= y_new
}

callee_tell() {
	MsgBox x=%x%`, y=%y%
}
is called by caller.ahk =

Code: Select all

#Warn ; will warn that callee_set is never executed
callee_tell()
then x and y will be undefined.
(This extremely simplified example might tempt the reply “Just put the first three lines of callee.ahk in caller.ahk”. But in reality that would be an ugly hack – a gross violation of some of the most fundamental coding principles, such as ‘Don’t repeat yourself’ and the ‘Single Responsibility Principle’.)

Re: initialization in a library

Posted: 14 Nov 2022, 02:06
by Micromegas
Any ideas? This seemed like such a basic question to me that i was a bit embarrassed to ask.

Re: initialization in a library

Posted: 14 Nov 2022, 02:25
by william_ahk
I'm scared to reply but doesn't #include work?

Re: initialization in a library

Posted: 14 Nov 2022, 03:03
by Micromegas
Thank you for your prompt reply. Please don't be scared; it's well possible that there's something simple i overlooked.

And for this example you're right: #include should work. But my example was oversimplified. So, sorry, it is getting more complicated, after all:

In reality, I have several libraries from which my code might use one or the other function. Differently from import in other languages, such as Python, #include doesn't encapsulate the functionality of each library. This means e.g. that there can be conflicts (such as use of the same variable or label name). And it means that one library can prevent the next from executing its initialization code. What I'm looking for is a way to ensure that.

Re: initialization in a library  Topic is solved

Posted: 14 Nov 2022, 04:06
by william_ahk
Ah ok.
It's the responsibility of the library to encapsulate everything in a class. AHK only has #include which will put all functions in the global namespace.

Example:

Code: Select all

class callee {
	set(x_new, y_new) {
		this.x := x_new
		this.y := y_new
	}

	tell() {
		MsgBox % "x=" this.x ", y=" this.y
	}
}

callee.set(1,2)
callee.tell()

Re: initialization in a library

Posted: 14 Nov 2022, 10:37
by Micromegas
Thank you! This works with the following caller.ahk:

Code: Select all

#Warn 

#Include %A_ScriptDir%	; when both files are in the same directory, as for this test.
#include callee.ahk

callee.tell()