-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
table_ext.lua
69 lines (60 loc) · 1.28 KB
/
table_ext.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
require "underscore_alias"
_G.count = function (iter)
return reduce(iter, 0, function (a, x) return a+1 end)
end
_G.sum = function (iter)
return reduce(iter, 0, function (a, x) return a+x end)
end
-- Using sum+count would be two times slower and would consume the iterator
_G.mean = function (iter)
local sum, count = 0, 0
each(iter, function (x)
sum = sum + x
count = count + 1
end)
if count == 0 then
return 0
else
return sum / count
end
end
_G.count_pairs = function (iter)
local n = 0
for _ in pairs(iter) do
n = n+1
end
return n
end
function table.sorted_pairs(t, order)
-- collect the keys
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
-- if order function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if order then
table.sort(keys, function(a,b) return order(t, a, b) end)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
function table.contains(tab, val)
for k, v in pairs(tab) do
if v == val then return true end
end
return false
end
function table:copy ()
local t = {}
for k, v in pairs(self) do
t[k] = v
end
return t
end