# 《Lua程序设计》之 闭包

### 九、闭包

##### 9.1 函数是第一类值

a = {p = print}
a.p("Hello World")
print = math.sin
a.p(print(1))
math.sin = a.p
math.sin(10,20)

--打印
Hello World
0.8414709848079
10  20

function foo(x) return 2*x end
--等价于
foo = function(x) return 2*x end --右边就是函数构造器，与表构造器{}相似

network = {
{name = 'grauna'},
{name = 'arraial'},
{name = 'lua'},
{name = 'derain'}
}
table.sort( network, function(a,b) return(a.name > b.name) end)

for i,t in pairs(network) do
for k,v in pairs(t) do
print(k,v)
end
end

--print
name    lua
name    grauna
name    derain
name    arraial

##### 9.2 非全局函数

Lib = {
foo = function(x,y) return x+y end,
goo = function(x,y) return x-y end
}
print(Lib.foo(10,6))
print(Lib.goo(10,6))

Lib = {}
function Lib.foo(x,y) return x+y end
function Lib.goo(x,y) return x-y end

local function f(param)
body
end

local fact = function (n)
if n==0 then return 1
else return n*fact(n-1)
end
end

fact(10)

local fact
fact = function (n)
if n==0 then return 1
else return n*fact(n-1)
end
end

print(fact(10))

local f
f = function (param)
body
end

local f --“前向” 声明

local function g ( )
some code f() some code
end

function f()   --这里的f是上面声明的f，不需要再用local修饰
some code g() some code
end
##### 9.2 词法定界

for i,v in ipairs(names) do
print(i,v)
end
end

names = {"Peter","Paul","Mary"}
grades = {Mary = 10,Paul = 7,Peter = 8}

function newCounter()
local count = 0
return function ()
count = count + 1
return count
end
end

c1 = newCounter()
c2 = newCounter()
print(c1())         --1
print(c1())         --2
print(c2())         --1
print(c1())         --3
print(c2())         --2

do              -- do 限制局部变量oldOpen的作用范围
local oldOpen = io.open
local access_OK = function (filename,mode)
check access
end
io.open = function (filename,mode)
if access_OK(filename,mode) then
return oldOpen(filename,mode)
else