-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclosure.lua
More file actions
52 lines (41 loc) · 984 Bytes
/
closure.lua
File metadata and controls
52 lines (41 loc) · 984 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function createClosure()
local secret = "I'm a secret!" -- 这是一个局部变量
return function()
print(secret) -- 内部函数可以访问外部函数的局部变量
end
end
local myClosure = createClosure() -- 创建闭包
myClosure() -- 输出 "I'm a secret!"
function newCounter()
local count = 0
return function()
count = count + 1
return count
end
end
c1 = newCounter()
print(type(c1))
print(c1())
print(c1())
print(count)
-- 每个闭包是独立的
c2 = newCounter()
print(c2())
print(c2())
print(c1())
-- 好像很平滑就理解了函数是第一类值
-- C++那种才不方便理解,因为一开始的抽象层级没有充分屏蔽底层细节
function F(x)
return {
set = function(y) x = y end,
get = function()
return x
end
}
end
o1 = F(10)
o2 = F(20)
print(o1.get(), o2.get())
o2.set(100)
o1.set(300)
print(o1.get(), o2.get())