functions.lua
17.3 KB
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
--[[
Copyright (c) 2011-2012 qeeplay.com
http://dualface.github.com/quick-cocos2d-x/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
--[[--
Convert to number.
@param mixed v
@return number
]]
function tonum(v, default)
default = default or 0
return tonumber(v) or default
end
--[[--
Convert to integer.
@param mixed v
@return number(integer)
]]
function toint(v)
return math.round(tonumber(v))
end
--[[--
Convert to boolean.
@param mixed v
@return boolean
]]
function tobool(v)
return (v ~= nil and v ~= false)
end
--[[--
Convert to table.
@param mixed v
@return table
]]
function totable(v)
if type(v) ~= "table" then v = {} end
return v
end
--[[--
Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). string.format() alias.
@param string format
@param mixed ...
@return string
]]
function format(...)
return string.format(...)
end
--[[--
Creating a copy of an table with fully replicated properties.
**Usage:**
-- Creating a reference of an table:
local t1 = {a = 1, b = 2}
local t2 = t1
t2.b = 3 -- t1 = {a = 1, b = 3} <-- t1.b changed
-- Createing a copy of an table:
local t1 = {a = 1, b = 2}
local t2 = clone(t1)
t2.b = 3 -- t1 = {a = 1, b = 2} <-- t1.b no change
@param mixed object
@return mixed
]]
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
--[[--
Create an class.
**Usage:**
local Shape = class("Shape")
-- base class
function Shape:ctor(shapeName)
self.shapeName = shapeName
printf("Shape:ctor(%s)", self.shapeName)
end
function Shape:draw()
printf("draw %s", self.shapeName)
end
--
local Circle = class("Circle", Shape)
function Circle:ctor()
Circle.super.ctor(self, "circle") -- call super-class method
self.radius = 100
end
function Circle:setRadius(radius)
self.radius = radius
end
function Circle:draw() -- overrideing super-class method
printf("draw %s, raidus = %0.2f", self.shapeName, self.raidus)
end
--
local Rectangle = class("Rectangle", Shape)
function Rectangle:ctor()
Rectangle.super.ctor(self, "rectangle")
end
--
local circle = Circle.new() -- output: Shape:ctor(circle)
circle:setRaidus(200)
circle:draw() -- output: draw circle, radius = 200.00
local rectangle = Rectangle.new() -- output: Shape:ctor(rectangle)
rectangle:draw() -- output: draw rectangle
@param string classname
@param table|function super-class
@return table
]]
function class(classname, super)
local superType = type(super)
local cls
if superType ~= "function" and superType ~= "table" then
superType = nil
super = nil
end
if superType == "function" or (super and super.__ctype == 1) then
-- inherited from native C++ Object
cls = {}
if superType == "table" then
-- copy fields from super
for k,v in pairs(super) do cls[k] = v end
cls.__create = super.__create
cls.super = super
else
cls.__create = super
cls.ctor = function() end
end
cls.__cname = classname
cls.__ctype = 1
function cls.new(...)
local instance = cls.__create(...)
-- copy fields from class to native object
for k,v in pairs(cls) do instance[k] = v end
instance.class = cls
-- 覆盖热更新的方法
pcall(function()
if _hotfixClass and _hotfixClass[cls.__cname] then
for _, func in ipairs(_hotfixClass[cls.__cname]) do
func(instance) -- 绑定新的方法
end
end
end)
instance:ctor(...)
return instance
end
else
-- inherited from Lua Object
if super then
cls = clone(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
-- 覆盖热更新的方法
pcall(function()
if _hotfixClass and _hotfixClass[cls.__cname] then
for _, func in ipairs(_hotfixClass[cls.__cname]) do
func(instance) -- 绑定新的方法
end
end
end)
instance:ctor(...)
return instance
end
end
return cls
end
--[[--
]]
function import(moduleName, currentModuleName)
local currentModuleNameParts
local moduleFullName = moduleName
local offset = 1
while true do
if string.byte(moduleName, offset) ~= 46 then -- .
moduleFullName = string.sub(moduleName, offset)
if currentModuleNameParts and #currentModuleNameParts > 0 then
moduleFullName = table.concat(currentModuleNameParts, ".") .. "." .. moduleFullName
end
break
end
offset = offset + 1
if not currentModuleNameParts then
if not currentModuleName then
local n,v = debug.getlocal(3, 1)
currentModuleName = v
end
currentModuleNameParts = string.split(currentModuleName, ".")
end
table.remove(currentModuleNameParts, #currentModuleNameParts)
end
return require(moduleFullName)
end
--[[--
]]
function handler(target, method)
return function(...) return method(target, ...) end
end
--[[--
]]
function handlerObject(object)
return function(event, ...)
if object[event] then
return object[event](object, ...)
end
end
end
--[[--
Returns a associative table containing the matching values.
@param table arr
@param table names
@return array
]]
function export(arr, names)
local args = {}
for k, def in pairs(names) do
if type(k) == "number" then
args[def] = arr[def]
else
args[k] = arr[k] or def
end
end
return args
end
--[[--
hecks if the given key or index exists in the table.
@param table arr
@param mixed key
@return boolean
]]
function isset(arr, key)
return type(arr) == "table" and arr[key] ~= nil
end
--[[--
Rounds a float.
@param number num
@return number(integer)
]]
function math.round(num)
return math.floor(num + 0.5)
end
--[[--
Checks whether a file exists.
@param string path
@return boolean
]]
function io.exists(path)
local file = io.open(path, "r")
if file then
io.close(file)
return true
end
return false
end
--[[--
Reads entire file into a string, or return FALSE on failure.
@param string path
@return string
]]
function io.readfile(path)
local file = io.open(path, "r")
if file then
local content = file:read("*a")
io.close(file)
return content
end
return nil
end
--[[--
Write a string to a file, or return FALSE on failure.
@param string path
@param string content
@param string mode
@return boolean
### Note:
The mode string can be any of the following:
"r": read mode
"w": write mode;
"a": append mode;
"r+": update mode, all previous data is preserved;
"w+": update mode, all previous data is erased; (the default);
"a+": append update mode, previous data is preserved, writing is only allowed at the end of file.
]]
function io.writefile(path, content, mode)
mode = mode or "w+"
local file = io.open(path, mode)
if file then
if file:write(content) == nil then return false end
io.close(file)
return true
else
return false
end
end
--[[--
Returns information about a file path.
**Usage:**
local path = "/var/app/test/abc.png"
local pathinfo = io.pathinfo(path)
-- pathinfo.dirname = "/var/app/test/"
-- pathinfo.filename = "abc.png"
-- pathinfo.basename = "abc"
-- pathinfo.extname = ".png"
@param string path
@return table
]]
function io.pathinfo(path)
local pos = string.len(path)
local extpos = pos + 1
while pos > 0 do
local b = string.byte(path, pos)
if b == 46 then -- 46 = char "."
extpos = pos
elseif b == 47 then -- 47 = char "/"
break
end
pos = pos - 1
end
local dirname = string.sub(path, 1, pos)
local filename = string.sub(path, pos + 1)
extpos = extpos - pos
local basename = string.sub(filename, 1, extpos - 1)
local extname = string.sub(filename, extpos)
return {
dirname = dirname,
filename = filename,
basename = basename,
extname = extname
}
end
--[[--
Gets file size, or return FALSE on failure.
@param string path
@return number(integer)
]]
function io.filesize(path)
local size = false
local file = io.open(path, "r")
if file then
local current = file:seek()
size = file:seek("end")
file:seek("set", current)
io.close(file)
end
return size
end
--[[--
Count all elements in an table.
@param table t
@return number(integer)
]]
function table.nums(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
end
return count
end
--[[--
Return all the keys or a subset of the keys of an table.
**Usage:**
local t = {a = 1, b = 2, c = 3}
local keys = table.keys(t)
-- keys = {"a", "b", "c"}
@param table t
@return table
]]
function table.keys(t)
local keys = {}
for k, v in pairs(t) do
keys[#keys + 1] = k
end
return keys
end
--[[--
Return all the values of an table.
**Usage:**
local t = {a = "1", b = "2", c = "3"}
local values = table.values(t)
-- values = {1, 2, 3}
@param table t
@return table
]]
function table.values(t)
local values = {}
for k, v in pairs(t) do
values[#values + 1] = v
end
return values
end
--[[--
Merge tables.
**Usage:**
local dest = {a = 1, b = 2}
local src = {c = 3, d = 4}
table.merge(dest, src)
-- dest = {a = 1, b = 2, c = 3, d = 4}
@param table dest
@param table src
]]
function table.merge(dest, src)
for k, v in pairs(src) do
dest[k] = v
end
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
function table.maxkey(tb)
local max = 0
for k, v in pairs(tb) do
if k > max then
max = k
end
end
return max
end
function table.minkey(tb)
local min = math.huge
for k, v in pairs(tb) do
if k < min then
min = k
end
end
return min
end
--[[--
Convert special characters to HTML entities.
The translations performed are:
- '&' (ampersand) becomes '&'
- '"' (double quote) becomes '"'
- "'" (single quote) becomes '''
- '<' (less than) becomes '<'
- '>' (greater than) becomes '>'
@param string input
@return string
]]
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[">"] = ">"
--[[--
Inserts HTML line breaks before all newlines in a string.
Returns string with '<br />' inserted before all newlines (\n).
@param string input
@return string
]]
function string.nl2br(input)
return string.gsub(input, "\n", "<br />")
end
--[[--
Returns a HTML entities formatted version of string.
@param string input
@return string
]]
function string.text2html(input)
input = string.gsub(input, "\t", " ")
input = string.htmlspecialchars(input)
input = string.gsub(input, " ", " ")
input = string.nl2br(input)
return input
end
--[[--
Split a string by string.
@param string str
@param string delimiter
@return table
]]
function string.split(str, 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
--[[--
Strip whitespace (or other characters) from the beginning of a string.
@param string str
@return string
]]
function string.ltrim(str)
return string.gsub(str, "^[ \t\n\r]+", "")
end
--[[--
Strip whitespace (or other characters) from the end of a string.
@param string str
@return string
]]
function string.rtrim(str)
return string.gsub(str, "[ \t\n\r]+$", "")
end
--[[--
Strip whitespace (or other characters) from the beginning and end of a string.
@param string str
@return string
]]
function string.trim(str)
str = string.gsub(str, "^[ \t\n\r]+", "")
return string.gsub(str, "[ \t\n\r]+$", "")
end
--[[--
Make a string's first character uppercase.
@param string str
@return string
]]
function string.ucfirst(str)
return string.upper(string.sub(str, 1, 1)) .. string.sub(str, 2)
end
--[[--
@param string str
@return string
]]
function string.urlencodeChar(char)
return "%" .. string.format("%02X", string.byte(c))
end
--[[--
URL-encodes string.
@param string str
@return string
]]
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%.%- ])", string.urlencodeChar)
-- convert spaces to "+" symbols
return string.gsub(str, " ", "+")
end
--[[--
Get UTF8 string length.
@param string str
@return int
]]
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
--[[--
Return formatted string with a comma (",") between every group of thousands.
**Usage:**
local value = math.comma("232423.234") -- value = "232,423.234"
@param number num
@return string
]]
function string.formatNumberThousands(num)
local formatted = tostring(tonumber(num))
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.find(t, item)
return table.keyOfItem(t, item) ~= nil
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.removeItem(list, item, removeAll)
local rmCount = 0
for i = 1, #list do
if list[i - rmCount] == item then
table.remove(list, i - rmCount)
if removeAll then
rmCount = rmCount + 1
else
break
end
end
end
end
function table.array2Table(arr)
local ret = {}
for i=1, #arr, 2 do
ret[arr[i]] = arr[i+1]
end
return ret
end