Created
April 9, 2013 14:32
-
-
Save dermotbalson/5346152 to your computer and use it in GitHub Desktop.
9. Coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function setup() | |
parameter.action('Run_without_coroutine',bigJob) | |
parameter.action('Run_with_coroutine',WithCoroutine) | |
end | |
function WithCoroutine() | |
cos=coroutine.create(bigJobCos) | |
coroutine.resume(cos) | |
end | |
function bigJob() | |
output.clear() --clear print output area | |
for n=1,10 do | |
--time consuming code here | |
for j=1,5000000 do local x=3.1^4.5 end | |
print('completed',n) | |
end | |
print('Job done!') | |
end | |
function bigJobCos() | |
output.clear() --clear print output area | |
progress=0 --used for printing status of job | |
for n=1,10 do | |
--time consuming code here | |
for j=1,5000000 do local x=3.1^4.5 end | |
progress=n | |
coroutine.yield() | |
end | |
progress=-1 --signal end of job | |
if cos then cos=nil end --just to be tidy, kill this off | |
end | |
function draw() | |
if progress then --only report if job is running, ie n is not nil | |
if progress>0 then | |
print('completed',progress) --print progress of job | |
coroutine.resume(cos) --carry on calculating | |
elseif progress==-1 then | |
print('Job done!') | |
progress=nil --to stop any more printing | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment