Functions that call themselves are called recursive.
When you call a function, you compute it, and get it's result, and then keep working. Because you need to "keep working" with all of your local variables in-tact, you have to set aside a chunk of "stack" for each 'deeper' call.
Eventually, you run out, and this is called a stack overflow.
You can approximate the size of the stack by doing something like this:
_G.c = 0
function f()
_G.c = _G.c + 1
f()
end
f()
print(_G.c)
(The Lua stack is much bigger than most programming languages' defaults. You don't normally hit it unless it's never going to be done)
However, I can use tail recursion to make this not happen.
c = 0
function g()
c = c + 1
return g()
end
g()
Because you are explicitly returning just the result of the function call, you don't need to "remember" the current function, and thus it takes no extra resources.
This is called a tail call, and it's basically equivalent to not using recursion at all.
The key is to return exactly one function call (and don't do anything with the result).
return f()
return f(1, 2, 3)
return f(1 + 9 + g())
return f(f(x))
return 1 + f()
return f(), f()
If what you mean is something as simple as "keep doing this time after time", you should use iteration, since that's the clearer way of describing what you mean.
However, doing things recursively definitely makes more sense sometimes.
Tail Recursion Example
Here's a normal recursive definition of factorial
function factorial(n)
if n == 0 then
return 1
end
return n * factorial(n - 1)
end
Notice that since I'm doing something to the result of the factorial(n-1) call, this is not a tail recursive call.
To write this tail-recursively, we're going to instead write a similar function. That function I'll just call f. f(n, c) will return n! * c.
In particular, that means
f(n, c) = n! * c = n*(n-1)! * c = (n-1)! * (n*c) = f(n - 1, n * c)
Note that we've avoided doing anything to the result of f this time!
function f(n, c)
if n == 0 then
return c
end
return f(n - 1, n * c)
end
function factorial(n)
return f(n, 1)
end