例子的 coroutine |
|
下列範例反向列印一個字串。它使用 coroutine 和遞迴來進行實作(沒有任何表格)。
do local wrap, yield = coroutine.wrap, coroutine.yield local function putrev(w) if w then putrev(yield()) io.write(w) end end function prevchar(s) local p = wrap(putrev) p"\n" string.gsub(s, ".", p) p() end -- don't look at this one until you understand the first one function prevword(s) local p = wrap(putrev) local function q(a, b) p(a) p(b) end p"\n" string.gsub(s, "(%S+)(%s*)", q) p() end end > prevchar "This is a test" tset a si sihT > prevword "This is a test" test a is This >
-- RiciLake
以下是利用 coroutine 控制反轉的兩種不同方式
for k in coroutine.wrap(function() table.foreach(_G, coroutine.yield) end) do print(k) end table.foreach(_G, coroutine.wrap(function(k) print(k) for k in coroutine.yield do print(k) end end))
不幸地,這兩種方式都不能使用在標準的 Lua。找出它們不能運作的真正原因,你就會茅塞頓開。或者直接取得 Coco 或 RVM 的延伸套件,這樣就能正常運作(有關最新可用性,請參閱郵件清單)。