# 【笨木头Lua专栏】基础补充03：闭合函数、非全局函数与函数的尾调用

## 1.闭合函数（closure）

```
1234567function count()
local i = 0;
return function()
i = i + 1;
return i;
end
end

```

```
1234    local func = count();
print(func());
print(func());
print(func());

```

[LUA-print] 1
[LUA-print] 2
[LUA-print] 3

```
1234567function count()
return function()
local i = 999;
i = i + 1;
return i;
end
end

```

```
1234    local func = count();
print(func());
print(func());
print(func());

```

[LUA-print] 1000
[LUA-print] 1000
[LUA-print] 1000

## 2.非全局函数

```
123local function mutou()

end

```

```
1234local mutou;
mutou = function ()

end

```

```
12345678local function mutou()
print("mutou");
return pangbai();
end

local function pangbai()
print("pangbai");
end

```

mutou函数里要调用pangbai函数。

```
1234567891011local mutou;
local pangbai;

mutou = function ()
print("mutou");
return pangbai();
end

pangbai = function ()
print("pangbai");
end

```

## 3.尾调用

```
123function mutou()
return count();
end

```

```
123function mutou()
return count() + 1;
end

```

```
1234567function foo(n)
if n > 0 then
return foo(n - 1);
else
return "end";
end
end

```

```
1print(foo(99999));

```

```
1234567function foo(n)
if n > 0 then
return foo(n - 1) + 0;
else
return "end";
end
end

```