1
+ local select = select
2
+ local type = type
3
+ local getmetatable = getmetatable
4
+ local xpcall = xpcall
5
+ local math_floor = math.floor
6
+ local math_ceil = math.ceil
7
+
1
8
table .unpack = unpack
2
9
3
10
table .pack = function (...)
4
11
return { n = select (' #' , ... ), ... }
5
12
end
6
13
7
- function defer (toBeClosed , callback )
8
- local ctype = type (toBeClosed )
9
- local meta = getmetatable (toBeClosed )
10
- if meta and meta .__close then
11
- local ok , result = xpcall (callback , log .error )
12
- meta .__close (toBeClosed )
13
- if ok then
14
- return result
15
- end
16
- elseif ctype == ' function' then
17
- local ok , result = xpcall (callback , log .error )
18
- toBeClosed ()
19
- if ok then
20
- return result
21
- end
22
- else
23
- local ok , result = xpcall (callback , log .error )
24
- if ok then
25
- return result
26
- end
27
- end
28
- end
29
-
30
14
math.maxinteger = 0x7FFFFFFF LL
31
- function math . tointeger (x )
15
+ local function tointeger (x )
32
16
if type (x ) ~= " number" then
33
17
return nil
34
18
end
35
19
36
- local int = x >= 0 and math.floor (x ) or math.ceil (x )
20
+ local int = x >= 0 and math_floor (x ) or math_ceil (x )
37
21
38
22
if int == x then
39
23
return int
@@ -42,10 +26,62 @@ function math.tointeger(x)
42
26
end
43
27
end
44
28
29
+ math .tointeger = tointeger
30
+
45
31
function math .type (x )
46
32
if type (x ) == " number" then
47
- return math. tointeger (x ) and " integer" or " number"
33
+ return tointeger (x ) and " integer" or " number"
48
34
else
49
35
return nil
50
36
end
51
37
end
38
+
39
+ local coroutine_resume = coroutine.resume
40
+ local coroutine_status = coroutine.status
41
+ local coroutine_running = coroutine.running
42
+
43
+ local cancel_table = setmetatable ({}, { __mode = ' kv' })
44
+
45
+ function coroutine .resume (co , ...)
46
+ if cancel_table [co ] then
47
+ return false , ' cannot resume dead coroutine'
48
+ end
49
+
50
+ return coroutine_resume (co , ... )
51
+ end
52
+
53
+ function coroutine .status (co )
54
+ if cancel_table [co ] then
55
+ return ' dead'
56
+ end
57
+
58
+ return coroutine_status (co )
59
+ end
60
+
61
+ function coroutine .close (co )
62
+ if coroutine_status (co ) == ' suspended' then
63
+ cancel_table [co ] = true
64
+ end
65
+ end
66
+
67
+ function defer (toBeClosed , callback )
68
+ local ctype = type (toBeClosed )
69
+ local meta = getmetatable (toBeClosed )
70
+ local closeCallback = nil
71
+ local ok , result
72
+
73
+ local co = coroutine_running ()
74
+ if coroutine.status (co ) ~= ' dead' then
75
+ ok , result = xpcall (callback , log .error )
76
+ end
77
+
78
+ if meta and meta .__close then
79
+ meta .__close (toBeClosed )
80
+ elseif ctype == ' function' then
81
+ toBeClosed ()
82
+ end
83
+
84
+ if ok then
85
+ return result
86
+ end
87
+ end
0 commit comments