← Back to Lua Course | Chapter 7: Coroutines | Lesson 5 of 7

Generators क्या हैं

एक generator values की एक sequence एक-एक करके produce करने के लिए एक coroutine इस्तेमाल करता है।

In this page:

  1. Generators

Generators

एक generator एक function है जो successive values yield करता है, और इसे coroutine.wrap में wrap करना एक for loop में इस्तेमाल होने लायक एक iterator देता है। Values lazily produce होती हैं, सिर्फ तब जब loop अगली वाली माँगे। यह infinite sequences के लिए भी काम करता है, जब तक loop खुद रुक जाए।

Note: एक for loop तब रुकता है जब iterator nil return करे, इसलिए एक finished generator loop खत्म कर देता है।

उदाहरण: Generators

lua
local function range(n)
  return coroutine.wrap(function()
    for i = 1, n do coroutine.yield(i) end
  end)
end
for v in range(4) do io.write(v, " ") end
print()

local function fib()
  return coroutine.wrap(function()
    local a, b = 0, 1
    while true do
      coroutine.yield(a)
      a, b = b, a + b
    end
  end)
end
for v in fib() do
  if v > 50 then break end
  io.write(v, " ")
end
print()

-- Output:
-- 1 2 3 4
-- 0 1 1 2 3 5 8 13 21 34
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. yield करने की बजाय पहले पूरी list बनाना
  2. बिना break के एक infinite generator लिखना
  3. generator function को इसके result इस्तेमाल करने की बजाय call करना
चैप्टर सारांश
  • Values एक-एक करके yield करें
  • wrap इसे एक iterator में बदल देता है
  • Values lazily produce होती हैं
  • जब function nil return करे loop खत्म होता है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.