# Lua中的協同程式之resume-yield間的資料返回研究

1.resume的引數

resume函式除了第一個引數是協同程式外，還能繼續傳其他引數，如下程式碼：

local co = coroutine.create(function(name)
print(name);
end);
coroutine.resume(co, “resume param”);

resume第二個引數為“resume parame”，這個引數將會傳遞給協同程式的函式。

[LUA-print] resume param

2.resume函式的第二個返回值

local co = coroutine.create(function(name)
print(name);
coroutine.yield(“yield param”);
end);
local result, msg = coroutine.resume(co, “resume param”);
print(“msg:” .. msg);

[LUA-print] resume param
[LUA-print] msg:yield param

3.yield的返回值

local co = coroutine.create(function(name)
for i = 1, 2, 1 do
print(name);
print(“co:” .. coroutine.yield(“yield param”));
end
end);
for i = 1, 2, 1 do
print(“=========第” .. i .. “次執行：”)
local result, msg = coroutine.resume(co, “resume param”);
print(“msg:” .. msg);
end

[LUA-print] =========第1次執行：
[LUA-print] resume param
[LUA-print] msg:yield param
[LUA-print] =========第2次執行：
[LUA-print] co:resume param
[LUA-print] resume param
[LUA-print] msg:yield param

4.協同程式結束，主函式的返回值

local co = coroutine.create(function(name)
for i = 1, 2, 1 do
print(name);
print(“co:” .. coroutine.yield(“yield param”));
end
return “協同程式函式結束喇！”
end);
for i = 1, 3, 1 do
print(“=========第” .. i .. “次執行：”)
local result, msg = coroutine.resume(co, “resume param”);
print(“msg:” .. msg);
end

[LUA-print] =========第1次執行：
[LUA-print] resume param
[LUA-print] msg:yield param
[LUA-print] =========第2次執行：
[LUA-print] co:resume param
[LUA-print] resume param
[LUA-print] msg:yield param
[LUA-print] =========第3次執行：
[LUA-print] co:resume param
[LUA-print] msg:協同程式函式結束喇！

5.結束