经常会用到递归,虽然能解决很多问题,但其缺点很明显,有可能无法跳出造成死循环,能控制递归次数就可以避免这种情况。
用lua尝试了几种方法,第一种,在方法内定义一个变量计数:
function recursionTest()
local times = 0
if times < 10 then
times = times + 1
recursionTest()
end
if times == 0 then
print("outer round")
end
end
执行下来,是无法限制的,因为局部变量每次都会重置为0。接下来第2种:
local recurTimes = 0
function recursionTest2()
if recurTimes < 10 then
recurTimes = recurTimes + 1
recursionTest2()
end
end
这种方法可以控制次数,但是变量需要定义在方法体外,执行函数前都需要先把这个变量设为0,需要在递归方法外包一层,比较繁琐。于是有了第3种解决方案:
function recursion(str, t)
str = str or "first time "
t = t or 0
t = t + 1
print(str, t)
if t < 10 then
recursion("times:", t)
end
if t == 1 then
print("outer round")
end
end
在递归时传入一个自增变量,达到阈值时停止递归,执行最外层时无需传参,默认值为0,且可根据t的值判断当前的递归层数,可以在递归结束时,在最外层执行完之前做其他事情,一举两得。