RejectedSoftware Forums

Sign up

setTimer()

Hi Folks,

Quick question. Is there any way to pass an argument to setTimer()?
In my understanding 'evtimer_new(base, callback, arg)' in libevent will
take an arbitrary argument, but through vibe.d, it does not seem to take
such a parameter.

I can do it somehow passing inline block to achieve same thing, but I
want to have callback function separately, for mostly readability and
modularity purpose.

Thanks,

--Toshiaki

Re: setTimer()

Quick question. Is there any way to pass an argument to setTimer()?
In my understanding 'evtimer_new(base, callback, arg)' in libevent will
take an arbitrary argument, but through vibe.d, it does not seem to take
such a parameter.

The arg will always be a context pointer towards the timer instance that contains the delegate.

A delegate contains a function and context pointer. If you send a delegate that is enclosed in a function with variables inside this function, these variables will be saved on the GC in a context.

e.g.

void myFunction() {
int a = 5;
int b = 6;
int c = 7;
setTimer(10.seconds, { writeln(a + b + c); });

}

The second argument to setTimer will be a function pointer to the closure, and a context pointer containing a, b and c allocated onto the GC and the callback will be called properly.

If your delegate is a method in a class or a struct, there will be no GC allocations.

Learning to use delegates is the cleanest way to use "callback" functions in D, I've done very thorough research and it works ultimately almost exactly like std::function in C++, but cleaner.

Re: setTimer()

On 11/09/2014 05:16 PM, Etienne Cimon wrote:

Quick question. Is there any way to pass an argument to setTimer()?
In my understanding 'evtimer_new(base, callback, arg)' in libevent will
take an arbitrary argument, but through vibe.d, it does not seem to take
such a parameter.

The arg will always be a context pointer towards the timer instance that contains the delegate.

A delegate contains a function and context pointer. If you send a delegate that is enclosed in a function with variables inside this function, these variables will be saved on the GC in a context.

e.g.

void myFunction() {
int a = 5;
int b = 6;
int c = 7;
setTimer(10.seconds, { writeln(a + b + c); });

}

The second argument to setTimer will be a function pointer to the closure, and a context pointer containing a, b and c allocated onto the GC and the callback will be called properly.

If your delegate is a method in a class or a struct, there will be no GC allocations.

Learning to use delegates is the cleanest way to use "callback" functions in D, I've done very thorough research and it works ultimately almost exactly like std::function in C++, but cleaner.

Thanks, it helps me a lot.

--T