Skip to content

Instantly share code, notes, and snippets.

@DamonHao
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save DamonHao/387b77d886d8bcb5b97d to your computer and use it in GitHub Desktop.

Select an option

Save DamonHao/387b77d886d8bcb5b97d to your computer and use it in GitHub Desktop.
the usage of resume and yield
local function testRoutine()
co = coroutine.create(function (x)
for i = 1, 10 do
-- print("co", i)
coroutine.yield(i)
end
end)
print(coroutine.resume(co))
print(coroutine.resume(co))
print(coroutine.resume(co))
end
--[[
A call to resume returns, after the true that signals no errors,
any arguments passed to the corresponding yield.
Note, though from the point of the coroutine, the yield has not
yet return back when suspended, but arguments passed to yield will
be passed to the resume, and resume will return those values.
output:
true 30 10
--]]
local function testRoutine1()
co = coroutine.create(function (a, b)
coroutine.yield (a+b, a-b)
end
)
print(coroutine.resume(co, 20, 10))
end
--[[
Symmetrically, yield returns any extra arguments passed to the corresponding resume:
output:
co1 hi
true mark
co2 1 2
--]]
local function testRoutine2()
co = coroutine.create(function (x)
print("co1", x)
print("co2", coroutine.yield("mark"))
end)
print(coroutine.resume(co, "hi"))
coroutine.resume(co, 1, 2)
end
local function main()
-- testRoutine()
-- testYield()
testRoutine2()
end
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment