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

Closures क्या हैं

एक closure एक ऐसा function है जो जहाँ से यह बना वहाँ के local variables याद रखता है।

In this page:

  1. Closures

Closures

जब एक function दूसरे function के अंदर define होता है यह outer function के local variables इस्तेमाल कर सकता है, जिन्हें upvalues कहते हैं। ये variables outer function के return होने के बाद भी alive रहते हैं, इसलिए एक factory की हर call एक independent set बनाती है। Closures आमतौर पर counters, private state, और callbacks के लिए इस्तेमाल होते हैं।

Note: outer function की हर call fresh upvalues बनाती है, इसलिए separately बनाए counters एक-दूसरे में interfere नहीं करते।

उदाहरण: Closures

lua
local function counter()
  local n = 0
  return function()
    n = n + 1
    return n
  end
end
local c1, c2 = counter(), counter()
print(c1(), c1(), c1())
print(c2())

local fns = {}
for i = 1, 3 do fns[i] = function() return i end end
print(fns[1](), fns[2](), fns[3]())

-- Output:
-- 1	2	3
-- 1
-- 1	2	3
{# 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. यह उम्मीद करना कि सारे closures एक counter share करेंगे
  2. एक loop variable capture करना और एक shared copy की उम्मीद करना
  3. यह मान लेना कि local variables function के return होने पर मर जाते हैं भले ही capture हुए हों
चैप्टर सारांश
  • Inner functions outer locals देख सकते हैं
  • Captured variables upvalues हैं
  • हर factory call की अपनी state होती है
  • Counters और private data के लिए useful

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.