Defer

Discuss the future of the AutoHotkey language
iseahound
Posts: 460
Joined: 13 Aug 2016, 21:04
GitHub: iseahound

Defer

26 Oct 2018, 23:42

jeeswg wrote:
18 Oct 2018, 17:34
@iseahound: If higher level concepts have influenced your AutoHotkey v2 Development ideas, what about lower level concepts? Assembly language etc. Cheers.
Defer would allow functions to execute code after the function has returned. For reference this functionality already exists you can write return a, b:=a

With defer you can just write:

Code: Select all

function() {
Defer b := a
Return a
Its main use would be to free allocated memory after returning the contents of the memory.

https://tour.golang.org/flowcontrol/12
Helgef
Posts: 3924
Joined: 17 Jul 2016, 01:02
Contact:

Re: Defer

27 Oct 2018, 09:30

It can be useful :thumbup:.
For reference this functionality already exists you can write return a, b:=a
For reference, no, it is not available. In v1, it evaluates the sub-expressions from left to right, before the function returns at that specific return statement, and returns the leftmost result. In v2, (a, b:=a) is evaluated from left to right, but the expression returns the result from the rightmost sub-expression.

Cheers.

Edit, spoiler doesn't seem to work. Spoiler-tag:
Simple function example, having similar effect,

Code: Select all

f 123
f(a){
	b := defer( () => free(a) )
	return msgbox('return line')
	free(p){
		msgbox p
	}
}

defer(f){
	return { base: { __delete : f } }
}
iseahound
Posts: 460
Joined: 13 Aug 2016, 21:04
GitHub: iseahound

Re: Defer

28 Oct 2018, 13:56

Yes your code is exactly right. Defer resembles the __Delete meta function of an object. I've found myself creating objects with only __New and __Delete to replicate this functionality.

Currently in v1 return a, DllCall("GlobalFree", "ptr", a) returns a and not the result of the DllCall. (I'm writing the above code from memory, and I'm pretty sure a is just a pointer to the data. )
lexikos
Posts: 6586
Joined: 30 Sep 2013, 04:07
GitHub: Lexikos

Re: Defer

12 May 2019, 20:44

Its main use would be to free allocated memory after returning the contents of the memory.
Free it when?

It seems to me that you should simply be using __delete if you are returning a resource which needs to be managed. It should probably be enclosed in a class, not used directly.
return a, DllCall("GlobalFree", "ptr", a)
This code is broken. You are returning a dangling pointer. You should free it after the caller finishes with it, not before the caller gets a chance to use it.

If what you want is a direct alternative to return a, b(), you can just use return (b(), a) or return (r := a, b(), r).

For the case of allocating a simple block of memory (and possibly writing a struct or binary data to it), you should use BufferAlloc() in v2.0-a103 and return the Buffer object.

Return to “AutoHotkey v2 Development”

Who is online

Users browsing this forum: No registered users and 8 guests