[v2.0.2] Closures do not capture variables Topic is solved

Report problems with documented functionality
User avatar
thqby
Posts: 397
Joined: 16 Apr 2021, 11:18
Contact:

[v2.0.2] Closures do not capture variables

Post by thqby » 28 Jan 2023, 20:16

Code: Select all

class test {
	__Delete() => OutputDebug('del`n')
	__New(fn) {
		this.v := ''
		this.r := ''
		t := reject
		resolve(val) {
			if 0
				val.then(resolve, reject)	; `this` is not captured, the destructor is called before the function is executed. In theory, this is a circular reference
				; val.then(resolve, t)		; work
				; val.then(reject)		; work
				; val.then(resolve)		; work
			this.v := val
		}
		reject(reason) {
			this.r := reason
		}
		fn(resolve)
	}
}

test(e => SetTimer(() => e(1), -500))
Sleep(600)

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

Re: [v2.0.2] Closures do not capture variables  Topic is solved

Post by lexikos » 19 Jun 2023, 05:52

Fixed by v2.0.3.

It is not the case that this was not captured, but that the block of "free variables" was deleted prematurely.

Merely refering to the functions by their formally defined names (which are constants) does not create a circular reference.
It is best not to store a reference to a closure in any of the closure's own free variables, since that creates a circular reference which must be broken (such as by clearing the variable) before the closure can be freed. However, a closure may safely refer to itself and other closures by their original variables without creating a circular reference.
Source: Functions - Definition & Usage | AutoHotkey v2
The bug was within the mechanism which allows this.

Post Reply

Return to “Bug Reports”