Closures क्या हैं
एक closure एक ऐसा function है जो जहाँ से यह बना वहाँ के local variables याद रखता है।
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- यह उम्मीद करना कि सारे closures एक counter share करेंगे
- एक loop variable capture करना और एक shared copy की उम्मीद करना
- यह मान लेना कि local variables function के return होने पर मर जाते हैं भले ही capture हुए हों
चैप्टर सारांश
- Inner functions outer locals देख सकते हैं
- Captured variables upvalues हैं
- हर factory call की अपनी state होती है
- Counters और private data के लिए useful
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: