nested functions with assume-global

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
Archimede
Posts: 534
Joined: 25 Nov 2021, 09:49
Location: Switzerland / Italy

nested functions with assume-global

Post by Archimede » 01 May 2024, 10:14

Hallo.
I have this nested functions:

Code: Select all

outer(x)
{
    inner1(y)
    {
		global

        iTest := 1
    }
    inner2(z)
    {
		global

        inner1(1)
    }
}
into inner2(z), if I use
global
I obtain this warning:
"Warning: This variable appears to never be assigned a value."
if I no use
global
it seem works: why?
Is it possible use
global
without generate any problem?
I tested to declare
Global
into the outer(...) function is like to declare Global into all nested functions: then what is the meaning to declare Global into any nested function?

Rohwedder
Posts: 7705
Joined: 04 Jun 2014, 08:33
Location: Germany

Re: nested functions with assume-global

Post by Rohwedder » 02 May 2024, 10:27

Hallo,
the "assume global" mode of inner2() apparently causes it to regard the inner1() function as a global variable. Try:

Code: Select all

#Requires AutoHotkey v2.0
#Warn All, Off
outer(1)
ListVars
outer(x)
{
	inner1(y)
    {
		global
		SoundBeep(4000, 20)
        iTest := 1
    }
    inner2(z)
    {
		global
		SoundBeep(1000, 20)
        Try inner1(1)
    }
	inner1(1)
	inner2(2)
}
2 SoundBeeps happen and there is a global variable inner1[0 of 0]
Now remove the "global" from inner(2)
3 SoundBeeps happen and there is no global variable inner1[0 of 0]
The third SoundBeep proves that inner1() is now called as a function.

Archimede
Posts: 534
Joined: 25 Nov 2021, 09:49
Location: Switzerland / Italy

Re: nested functions with assume-global

Post by Archimede » 02 May 2024, 17:36

Then what is exactly the meaning of Global into a nested function?

lexikos
Posts: 9631
Joined: 30 Sep 2013, 04:07
Contact:

Re: nested functions with assume-global

Post by lexikos » 02 May 2024, 20:47

One answer is directly stated in the documentation.
Assume-global mode: If a function needs to access or create a large number of global variables, it can be defined to assume that all its variables are global (except its parameters)
Source: Functions - Definition & Usage | AutoHotkey v2
The meaning does not change just because the function is nested. A nested function can be used to do exactly that on behalf of the outer function (or any other function within the outer function), without making the outer function assume-global. The assume-global nested function can access global variables which have the same name as local variables of the outer function.

Post Reply

Return to “Ask for Help (v2)”