Scheduler and variable scope

View: New views
2 Messages — Rating Filter:   Alert me  

Scheduler and variable scope

by Eric Lyon :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I've encountered some surprising behavior from Scheduler. Watch what happens to the "extra" variable when executing the two different blocks of code. Can anyone explain why these two blocks behave differently?

TIA,

Eric


// first load this function


(


~run_scheduler = { | sc |

var delta = 0.1;

Routine {

while( { sc.isEmpty == false }, { 

sc.advance(delta); 

delta.wait;

});

}.play;

};

)


// block 1 (surprising)



(

var simp = Scheduler.new(SystemClock);

var extra; // level where this variable is declared makes a difference


8.do({| now |

3.do({| comp |

extra = comp * comp;

("OUTSIDE event" + now + "component" + comp + "extra" + extra).postln;

simp.sched(now, {("event" + now + "component" + comp + "extra" + extra).postln});

});

});

~run_scheduler.value( simp );

)


// block 2 (better behavior)

(

var simp = Scheduler.new(SystemClock);


8.do({| now |

3.do({| comp |

var extra;

extra = comp * comp;

("OUTSIDE event" + now + "component" + comp + "extra" + extra).postln;

simp.sched(now, {("event" + now + "component" + comp + "extra" + extra).postln});

});

});

~run_scheduler.value( simp );

)



Re: Scheduler and variable scope

by James Harkins-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On Jun 28, 2008, at 5:06 PM, Eric Lyon wrote:

I've encountered some surprising behavior from Scheduler. Watch what happens to the "extra" variable when executing the two different blocks of code. Can anyone explain why these two blocks behave differently?

Yes, the first block might seem surprising at first, but this is normal behavior. It has to do with variable scope. In the first block, the "extra" variable is defined in the outermost scope, so it effectively, it behaves as a global variable in the context of that code block. When the loop is finished, "extra" is left with the value 4. The scheduled functions don't execute until the 8.do loop finishes, and once they start firing, there is nothing to change the value of the quasi-global "extra" variable.

By contrast, in the second block, "extra" is local to the function that adds items into the scheduler object. So, there are 24 distinct execution frames each with their own independent "extra" variable.

There are not many places in supercollider where variable scope is especially important, but scheduling is one of them.

See the "Scope" help file.

hjh


: H. James Harkins

: jamshark70@...

: http://www.dewdrop-world.net

.::!:.:.......:.::........:..!.::.::...:..:...:.:.:.:..:


"Come said the Muse,

Sing me a song no poet has yet chanted,

Sing me the universal."  -- Whitman


LightInTheBox - Buy quality products at wholesale price