-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtable_ext.lua
85 lines (78 loc) · 2.42 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
local M = {}
------------------------------------------------------------------------------
-- Return the number of instances of a value in a list
-- Adapted from: http://snippets.luacode.org/?p=snippets/Count_Item_Occurances_in_Table_24
------------------------------------------------------------------------------
local itemCount = function(list, value)
local count = 0
for i,v in pairs(list) do
if v == value then count = count + 1 end
end
return count
end
M.itemCount = itemCount
------------------------------------------------------------------------------
-- Return true if the given list has duplicate entries for the given value
-- This is a modified version of itemCount,
-- optimized for checking for duplicates
------------------------------------------------------------------------------
local hasDuplicateValues = function(list, value)
local result = false
local count = 0
for i,v in pairs(list) do
if v == value then count = count + 1 end
if count > 1 then
result = true
break
end
end
return result
end
M.hasDuplicateValues = hasDuplicateValues
------------------------------------------------------------------------------
-- Merge two tables
-- From: http://stackoverflow.com/questions/1283388/lua-merge-tables
------------------------------------------------------------------------------
local merge = function(t1, t2)
for k,v in pairs(t2) do
if type(v) == "table" then
if type(t1[k] or false) == "table" then
table.merge(t1[k] or {}, t2[k] or {})
else
t1[k] = v
end
else
t1[k] = v
end
end
return t1
end
M.merge = merge
------------------------------------------------------------------------------
-- Print the contents of a table
------------------------------------------------------------------------------
local tablePrint = function( t )
for i,v in pairs(t) do
if "table" == type(v) then
print(i .. " = [table]: ")
print("---")
M.print(v)
print("---")
else
print(i .. " = " .. v)
end
end
end
M.print = tablePrint
------------------------------------------------------------------------------
-- Wrap the values of a table inside single quotes
------------------------------------------------------------------------------
local quoteValues = function( t )
local result = {}
for i,v in pairs(t) do
result[i] = "'" .. v .. "'"
end
return result
end
M.quoteValues = quoteValues
return M