Variable hiding under a rock Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
Coiler
Posts: 114
Joined: 29 Nov 2020, 09:06

Variable hiding under a rock

Post by Coiler » 13 Jan 2021, 09:44

Is this kind of thing ok in AHK? And if so, does anyone know how this works, logically? Do variable references not get destroyed on scope exit? Or is it that conditions do not count as scopes?

Code: Select all

Function()
{
	if( rock )
		my_var := my_value

	do_some_stuff()
	
	if( rock )
		break_rock( my_var )
}
Thanks!

Edit: forgot bracket

User avatar
mikeyww
Posts: 27366
Joined: 09 Sep 2014, 18:38

Re: Variable hiding under a rock

Post by mikeyww » 13 Jan 2021, 11:51

I had no trouble with it. You can call a function within a function. Didn't it work when you tested it?

WatsonEnterprises
Posts: 19
Joined: 25 May 2020, 23:04

Re: Variable hiding under a rock  Topic is solved

Post by WatsonEnterprises » 13 Jan 2021, 20:46

https://www.autohotkey.com/docs/Functions.htm#Local
https://www.autohotkey.com/docs/Objects.htm#Reference_Counting

my_var's scope is just considered local to your function "Function" (assuming it isn't a global variable you declared eslsewhere). In a language like Java, variables declared inside an "if" block or "loop" block are considered out of scope once the block ends, but AHK doesn't do that.

That also means you can do things like this:

Code: Select all

for index, element in myArray {
	;..........
}
msgbox % index
If my_var was an object, AHK would automatically call my_var.__Delete() when the function ends (assuming no other variables have a reference that points to my_var).

User avatar
Coiler
Posts: 114
Joined: 29 Nov 2020, 09:06

Re: Variable hiding under a rock

Post by Coiler » 17 Jan 2021, 17:38

Okay, thanks for the info.
mikeyww wrote:
13 Jan 2021, 11:51
I had no trouble with it. You can call a function within a function. Didn't it work when you tested it?
Yeah, I did. And it worked. But I can't count the number of times I've been burned by trusting my own tests instead of learning to do something correctly. And this is a scenario where AHK is very different than pretty much every other programming language out there. Normally, such a variable would be destroyed when the block scope exits. And depending on how AHK works behind the scenes, it may still function correctly, even while using a variable that was deleted or had its memory recycled.

User avatar
mikeyww
Posts: 27366
Joined: 09 Sep 2014, 18:38

Re: Variable hiding under a rock

Post by mikeyww » 17 Jan 2021, 18:24

OK. Thank you, @Coiler.

Post Reply

Return to “Ask for Help (v1)”