-
Notifications
You must be signed in to change notification settings - Fork 22
/
utils.lua
697 lines (603 loc) · 14.7 KB
/
utils.lua
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
--[[
@ filename : db_helper.lua
@ author : [email protected] (kuzhu)
@ modify : 2017-03-25 10:53
@ company : shengzhenyiwang
]]
-- local skynet = require "skynet"
function tonum(v, base)
return tonumber(v, base) or 0
end
function toint(v)
return math.round(tonum(v))
end
function tobool(v)
return (v ~= nil and v ~= false)
end
function totable(v)
if type(v) ~= "table" then v = {} end
return v
end
function isset(arr, key)
local t = type(arr)
return (t == "table" or t == "userdata") and arr[key] ~= nil
end
function clone(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for key, value in pairs(object) do
new_table[_copy(key)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
function copy(object)
if not object then return object end
local new = {}
for k, v in pairs(object) do
local t = type(v)
if t == "table" then
new[k] = copy(v)
elseif t == "userdata" then
new[k] = copy(v)
else
new[k] = v
end
end
return new
end
--正向迭代器(key从小到大)
function Iterator(t)
local a = {}
for n in pairs(t) do
a[#a+1] = n
end
table.sort(a)
local i = 0
return function()
i = i + 1
return a[i], t[a[i]]
end
end
--反向迭代器(key从大到小)
function rIterator()
local a = {}
for n in pairs(t) do
a[#a+1] = n
end
table.sort(a, function(m, n) return m > n end)
local i = 0
return function()
i = i + 1
return a[i], t[a[i]]
end
end
function table.maxn(t)
local a = {}
for key, v in pairs(t) do
a[#a+1] = key
end
table.sort(a)
return a[#a]
end
function table.nums(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
end
return count
end
function table.empty(t)
return _G.next(t) == nil
end
function table.keys(t)
local keys = {}
for k, v in pairs(t) do
keys[#keys + 1] = k
end
return keys
end
function table.values(t)
local values = {}
for k, v in pairs(t) do
values[#values + 1] = v
end
return values
end
function table.merge(dest, src)
for k, v in pairs(src) do
dest[k] = v
end
end
--[[
table.zero(t, len) ==> memset(&t, 0, len)
]]
function table.zero(t, len)
assert(type(t) == "table")
for i=1, len do
t[i] = 0
end
end
--[[
table.malloc(len) ==> malloc(len)
]]
function table.malloc(len)
local t = {}
table.zero(t, len)
return t
end
--[[--
insert list.
**Usage:**
local dest = {1, 2, 3}
local src = {4, 5, 6}
table.insertto(dest, src)
-- dest = {1, 2, 3, 4, 5, 6}
dest = {1, 2, 3}
table.insertto(dest, src, 5)
-- dest = {1, 2, 3, nil, 4, 5, 6}
@param table dest
@param table src
@param table begin insert position for dest
]]
function table.insertto(dest, src, begin)
begin = tonumber(begin)
if begin == nil then
begin = #dest + 1
end
local len = #src
for i = 0, len - 1 do
dest[i + begin] = src[i + 1]
end
end
--[[
search target index at list.
@param table list
@param * target
@param int from idx, default 1
@param bool useNaxN, the len use table.maxn(true) or #(false) default:false
@param return index of target at list, if not return -1
]]
function table.indexof(list, target, from, useMaxN)
local len = (useMaxN and #list) or table.maxn(list)
if from == nil then
from = 1
end
for i = from, len do
if list[i] == target then
return i
end
end
return -1
end
function table.indexofKey(list, key, value, from, useMaxN)
local len = (useMaxN and #list) or table.maxn(list)
if from == nil then
from = 1
end
local item = nil
for i = from, len do
item = list[i]
if item ~= nil and item[key] == value then
return i
end
end
return -1
end
function table.removeItem(t, item, removeAll)
for i = #t, 1, -1 do
if t[i] == item then
table.remove(t, i)
if not removeAll then break end
end
end
end
--[[--
remove array(only in array not table).
**Usage:**
local dest = {1, 2, 3}
table.removeAll(dest)
-- dest = {}
@param table t
]]
function table.removeAll(t)
for i = #t, 1, -1 do
table.remove(t, i)
end
end
--[[--
remove array(can in table).
**Usage:**
local dest = {1, 2, 3}
table.removeAll(dest)
-- dest = {}
@param table t
]]
function table.clear(t)
for k, v in pairs(t) do
t[k] = nil
end
end
--[[--
create map by table.
**Usage:**
local dest = {1, 2}
table.map(dest, function(a, b) return {key=a, value=b} end)
-- dest = {
[1] = {key=1, value=1}
[2] = {key=2, value=2}
}
@param table t
]]
function table.map(t, fun)
for k,v in pairs(t) do
t[k] = fun(v, k)
end
end
function table.walk(t, fun)
for k,v in pairs(t) do
fun(v, k)
end
end
function table.filter(t, fun)
for k,v in pairs(t) do
if not fun(v, k) then
t[k] = nil
end
end
end
function table.find(t, item)
return table.keyOfItem(t, item) ~= nil
end
--[[--
create a unique map by table.
**Usage:**
local src = {1, 2, 1, 3, 1}
local dest = table.unique(src)
-- dest = {1, 2, 3}
@param table t
]]
function table.unique(t)
local r = {}
local n = {}
for i = #t, 1, -1 do
local v = t[i]
if not r[v] then
r[v] = true
n[#n + 1] = v
end
end
return n
end
function table.keyOfItem(t, item)
for k,v in pairs(t) do
if v == item then return k end
end
return nil
end
--二分查找
function table.bsearch(elements, x, field, low, high)
local meta = getmetatable(elements)
low = low or 1
high = high or (meta and meta.__len(elements) or #elements)
if low > high then
return -1
end
local mid = math.ceil((low + high) / 2)
local element = elements[mid]
local value = field and element[field] or element
if x == value then
while mid > 1 do
local prev = elements[mid - 1]
value = field and prev[field] or prev
if x ~= value then
break
end
mid = mid - 1
element = prev
end
return mid
end
if x < value then
return table.bsearch(elements, x, field, low, mid - 1)
end
if x > value then
return table.bsearch(elements, x, field, mid + 1, high)
end
end
function string.htmlspecialchars(input)
for k, v in pairs(string._htmlspecialchars_set) do
input = string.gsub(input, k, v)
end
return input
end
string._htmlspecialchars_set = {}
string._htmlspecialchars_set["&"] = "&"
string._htmlspecialchars_set["\""] = """
string._htmlspecialchars_set["'"] = "'"
string._htmlspecialchars_set["<"] = "<"
string._htmlspecialchars_set[">"] = ">"
function string.htmlspecialcharsDecode(input)
for k, v in pairs(string._htmlspecialchars_set) do
input = string.gsub(input, v, k)
end
return input
end
function string.nl2br(input)
return string.gsub(input, "\n", "<br />")
end
function string.text2html(input)
input = string.gsub(input, "\t", " ")
input = string.htmlspecialchars(input)
input = string.gsub(input, " ", " ")
input = string.nl2br(input)
return input
end
function string.split(str, delimiter)
str = tostring(str)
delimiter = tostring(delimiter)
if (delimiter=='') then return false end
local pos,arr = 0, {}
-- for each divider found
for st,sp in function() return string.find(str, delimiter, pos, true) end do
table.insert(arr, string.sub(str, pos, st - 1))
pos = sp + 1
end
table.insert(arr, string.sub(str, pos))
return arr
end
function string.ltrim(str)
return string.gsub(str, "^[ \t\n\r]+", "")
end
function string.rtrim(str)
return string.gsub(str, "[ \t\n\r]+$", "")
end
function string.trim(str)
str = string.gsub(str, "^[ \t\n\r]+", "")
return string.gsub(str, "[ \t\n\r]+$", "")
end
function string.ucfirst(str)
return string.upper(string.sub(str, 1, 1)) .. string.sub(str, 2)
end
local function urlencodeChar(char)
return "%" .. string.format("%02X", string.byte(c))
end
function string.urlencode(str)
-- convert line endings
str = string.gsub(tostring(str), "\n", "\r\n")
-- escape all characters but alphanumeric, '.' and '-'
str = string.gsub(str, "([^%w%.%- ])", urlencodeChar)
-- convert spaces to "+" symbols
return string.gsub(str, " ", "+")
end
function string.urldecode(str)
str = string.gsub (str, "+", " ")
str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonum(h,16)) end)
str = string.gsub (str, "\r\n", "\n")
return str
end
function string.utf8len(str)
local len = #str
local left = len
local cnt = 0
local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
while left ~= 0 do
local tmp = string.byte(str, -left)
local i = #arr
while arr[i] do
if tmp >= arr[i] then
left = left - i
break
end
i = i - 1
end
cnt = cnt + 1
end
return cnt
end
function string.utf8sub(str, start, last)
if start > last then
return ""
end
local len = #str
local left = len
local cnt = 0
local startByte = len + 1
local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
while left ~= 0 do
local tmp = string.byte(str, -left)
local i = #arr
while arr[i] do
if tmp >= arr[i] then
left = left - i
break
end
i = i - 1
end
cnt = cnt + 1
if cnt == start then
startByte = len - (left + i) + 1
end
if cnt == last then
return string.sub(str, startByte, len - left)
end
end
return string.sub(str, startByte, len)
end
function string.formatNumberThousands(num)
local formatted = tostring(tonum(num))
local k
while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
if k == 0 then break end
end
return formatted
end
--[[
从字符串创建表
]]
function table.fromString(str)
local func = load(str)
assert(func, string.format("chunk is invalid:%s", str))
return func()
end
function math.round(num)
return math.floor(num + 0.5)
end
--[[
随机函数
@param beginValue
@param endValue
]]
--local useMt19937 = skynet.getenv("useMt19937")
local useMt19937 = false
local mt19937 = nil
local __randomseed = nil
function math.rand(...)
--是否使用mt19937
if useMt19937 then
local i,j = ...
--初始化随机种
if not mt19937 then
mt19937 = require "mt19937"
mt19937.init(tostring(os.time()):reverse():sub(1, 6))
end
if j == nil then
--mt19937.randi(1,n)的返回值范围是[1,n)
return mt19937.randi(1, i+1)
else
return mt19937.randi(i, j+1)
end
return nil
else
if not __randomseed then
__randomseed = os.time()
end
__randomseed = __randomseed + 1
--把随机数种倒过来
math.randomseed(tostring(__randomseed):reverse():sub(1, 6))
--math.randomseed(__randomseed)
return math.random(...)
end
end
--[[
@随机打乱一个数组
]]
function math.random_shuffle(tb)
local array = copy(tb)
local length = #array
local function swap(i, j)
local tmp = clone(array[i])
array[i] = array[j]
array[j] = tmp
end
for i=1, length-1 do
local j = math.rand(i+1, length)
swap(i, j)
end
return array
end
function math.random_one(tb)
local length = #tb
return tb[math.rand(length)]
end
function GetDateTime(datetime)
if not datetime then
datetime = os.time()
end
return os.date("%Y-%m-%d %H:%M:%S", datetime)
end
--[[function class(classname, super)
local cls
if super then
cls = {}
setmetatable(cls, {__index = super})
cls.super = super
else
cls = {ctor = function() end}
end
cls.__cname = classname
cls.__ctype = 2 -- lua
cls.__index = cls
function cls.new(...)
local instance = setmetatable({}, cls)
instance.class = cls
instance:ctor(...)
return instance
end
return cls
end]]
--class = require "class"
function tableToString(root)
if root == nil then
return "nil"
end
local cache = { [root] = "." }
local function _dump(t,space,name)
local temp = {}
for k,v in pairs(t) do
local key = tostring(k)
if cache[v] then
table.insert(temp,"+" .. key .. " {" .. cache[v].."}")
elseif type(v) == "table" then
local new_key = name .. "." .. key
cache[v] = new_key
table.insert(temp,"+" .. key .. _dump(v,space .. (next(t,k) and "|" or " " ).. string.rep(" ",#key),new_key))
else
if type(v) == "string" then
table.insert(temp,"+" .. key .. " [\"" .. tostring(v).."\"]")
else
table.insert(temp,"+" .. key .. " [" .. tostring(v).."]")
end
end
end
return table.concat(temp,"\n"..space)
end
return (_dump(root, "",""))
end
local serverid
local uuid
function CreateUUID()
if not serverid then
serverid = skynet.getenv("serverid")
end
if not uuid then
uuid = require "uuid"
end
return uuid()..string.format("%02d", serverid)
end
--到目标时间还有多少s
--targetTime("12:00")
--return sec
function getIntervalFromNow(targetTime)
local hour, min = string.match(targetTime, "(%d+):(%d+)")
local hour = tonumber(hour)
local min = tonumber(min)
local dt = os.date("*t", os.time())
--当天的12:00
local endTime = os.time({
year= dt.year,
month = dt.month,
day = dt.day,
hour = hour,
min = min,
sec = 0
})
--当前时间
local interval = dt.hour * 60 + dt.min
--目标的时间
local targetInerval = hour * 60 + min
if interval < targetInerval then
return endTime - os.time()
else
return 86400 - (os.time() - endTime)
end
end