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

Recursion और Tail Calls

एक recursive function खुद को call करता है, और एक tail call इसे stack बढ़ाए बिना ऐसा करने देता है।

Recursion और Tail Calls

एक recursive function को local function से declare होना चाहिए ताकि इसका नाम इसकी अपनी body के अंदर visible हो। हर call stack space इस्तेमाल करता है, इसलिए बहुत deep recursion overflow कर जाता है। return f(x) फॉर्म की एक call Lua में एक proper tail call है और extra stack consume नहीं करती, इसलिए loops को tail recursion की तरह लिखा जा सकता है।

Note: local f = function ... end के साथ नाम f body के अंदर अभी visible नहीं है, इसलिए local function इस्तेमाल करें या पहले declare करें।

उदाहरण: Recursion and tail calls

lua
local function fact(n)
  if n <= 1 then return 1 end
  return n * fact(n - 1)
end
print(fact(5), fact(20))

local function sumTo(n, acc)
  acc = acc or 0
  if n == 0 then return acc end
  return sumTo(n - 1, acc + n)
end
print(sumTo(100000))

-- Output:
-- 120	2432902008176640000
-- 5000050000
{# 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. local f = function लिखना और इसके अंदर f call करना
  2. base case भूल जाना
  3. recursive call के बाद काम add करना और tail call खो देना
चैप्टर सारांश
  • Recursion के लिए local function इस्तेमाल करें
  • एक base case recursion रोकता है
  • return f(x) एक tail call है
  • Tail calls stack नहीं बढ़ाती

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.