我们先从一个错误的实例开始我们的讨论
local fact = function (n)
if n == 0 then
return 1 else
return n*fact(n-1)
end
上面这种方式导致 Lua 编译时遇到 fact(n-1)并不知道他是局部函数 fact,Lua 会去查找是否有这样的全局函数 fact。为了解决这个问题我们必须在定义函数以前先声明:
local fact
当然,定义采用哪种方式都行
local fact
function fact(n)
if n == 0 then
return 1
else
return n*fact(n-1)
end
end
local fact
fact = function (n)
if n == 0 then
return 1
else
return n*fact(n-1)
end
end
那么是不是对于递归函数,是不是一定要先申明呢?
答案是对于自己调用本身这类的直接递归函数,还有另一种简单方式
local function fact(n)
if n == 0 then
return 1
else
return n*fact(n-1)
end
end
对于非直接递归,则只有前一种方式