例子的 coroutine

lua-users home
wiki

這個頁面顯示了一些使用 coroutine 的技巧。

使用 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 的延伸套件,這樣就能正常運作(有關最新可用性,請參閱郵件清單)。


最近的變更 · 偏好設定
編輯 · 歷程
最後編輯於 2008 年 9 月 17 日星期三下午 12:47 GMT (diff)