Created
August 30, 2016 10:26
-
-
Save enghqii/58ab8121024ec5229a7b144d403cfcce to your computer and use it in GitHub Desktop.
Lua Coroutine Example
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
queue = {} | |
queue_max = 100 | |
producer = coroutine.create(function () | |
while #queue < queue_max do | |
local item = "Hello! "..#queue | |
table.insert(queue, item) | |
-- print(item .. " inserted") | |
end | |
coroutine.yield(coroutine.resume(consumer)) | |
end) | |
consumer = coroutine.create(function () | |
while #queue > 0 do | |
local item = table.remove(queue) -- pop | |
print(item) | |
end | |
coroutine.yield(coroutine.resume(producer)) | |
end) | |
coroutine.resume(producer); | |
--[[ | |
dict = {} | |
dict[producer] = coroutine.resume(producer) | |
dict[consumer] = coroutine.resume(consumer) | |
current = producer; | |
for i = 0, 100 do | |
coroutine.resume(dict[current]) | |
end | |
]] |
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
local sched = { | |
coroutines = {}, | |
} | |
function sched:start_coroutine(co) | |
table.insert(self.coroutines, co) | |
coroutine.resume(co) | |
end | |
function sched:stop_coroutine(co) | |
table.remove(self.coroutines, co) | |
end | |
function sched:update() | |
-- trace.print("==================") | |
for index, co in ipairs(self.coroutines) do | |
-- trace.print(coroutine.status(co)) | |
if coroutine.status(co) == 'suspended' then | |
coroutine.resume(co) | |
end | |
if coroutine.status(co) == 'dead' then | |
table.remove(self.coroutines, index) | |
trace.print("==================") | |
end | |
end | |
end | |
return sched |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment