Page 1 of 1

initializing a static using function that has a static

Posted: 06 Jan 2023, 16:04
by Relayer
I found the following unexpected behavior today. I am using 1.1.36.02
I initialize a static variable using a function which in turn uses a static variable. A blank is returned for the call to the function testFunc(). I appears that static variables are initialized in one pass in the order they are encountered. If I swap the position of the two functions in the example below, everything works as expected.

Relayer

Code: Select all

#SingleInstance Force
#NoEnv

Msgbox % testlib()
Msgbox % testFunc() ;returns blank
Return

testFunc()
{
	static x := testlib()
	
	Return x
}

testlib()
{
	static y := 42
	
	Return y
}

ExitApp
Escape::ExitApp

Re: initializing a static using function that has a static  Topic is solved

Posted: 06 Jan 2023, 18:43
by swagfag
what ure describing is the very behavior thats already documented: https://www.autohotkey.com/docs/v1/Functions.htm#InitStatic
Static var := expression is supported. All such expressions are evaluated immediately before the script's auto-execute section in the order they are encountered in the script.
this isnt likely to be ever changed in v1 ...on account of having been changed in v2

Re: initializing a static using function that has a static

Posted: 08 Jan 2023, 08:37
by Relayer
Thanks swagfag. I read that in the documentation but it didn't sink in until I was writing the posting and for grins swapped the position of the two functions in the script file and saw that it was an order of appearance issue.

I will need to keep this in mind when using statics in v1. I wasted a morning debugging what I thought was a working library function. It worked in all scripts but bombed in one script that used it to initialize a static.

Relayer

Re: initializing a static using function that has a static

Posted: 08 Jan 2023, 09:56
by andymbody
Relayer wrote:
06 Jan 2023, 16:04
I found the following unexpected behavior today.
This is interesting... Thanks for posting.

Thanks for the explanation @swagfag.

Re: initializing a static using function that has a static

Posted: 08 Jan 2023, 15:07
by Emile HasKey
The new IsSet function can be used as a workaround in AHK v1.1.35+.
It allows you to store functions in any order.
The IsSet workaround is unnecessary in AHK v2, but does work in AHK v2.

I've taken your example and modified the testlib function.

Code: Select all

#SingleInstance Force
#NoEnv

Msgbox % testlib()
Msgbox % testFunc() ;returns blank ;RETURNS 42 AFTER USING ISSET
Return

testFunc()
{
	static x := testlib()

	Return x
}

testlib()
{
	;static y := 42 ;OLD CODE
	static y ;NEW CODE
	if !IsSet(y) ;NEW CODE
		y := 42 ;NEW CODE

	Return y
}

ExitApp
Escape::ExitApp

Re: initializing a static using function that has a static

Posted: 10 Jan 2023, 16:03
by joefiesta
post redacted. I was way wrong in what I said.