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
|
--- ACF2 utility functions.
--
-- @module acf2.util
--[[
Copyright (c) 2012-2013 Kaarle Ritvanen
See LICENSE file for license details
--]]
local M = {}
--- set default value for a key in a table unless it is already set.
-- @param t the table
-- @param k the key
-- @param v the default value
-- @return the value `t[k]`
function M.setdefault(t, k, v)
if t[k] == nil then t[k] = v end
return t[k]
end
--- merge a table into another.
-- Copy values for all keys from `src` to `dst` and optionally keep existing
-- values.
-- @param dst the destination table
-- @param src the source table
-- @param preserve a boolean. If true then will existing entries in `dst` be
-- kept.
-- @return the destination table, `dst`
function M.update(dst, src, preserve)
for k, v in pairs(src) do
if not preserve or dst[k] == nil then dst[k] = v end
end
return dst
end
--- copy default vaules from one table to another.
-- Copy all entries in `src` to `dst` but keep any already existing values
-- in `dst`.
-- @param dst the destination table
-- @param src the source table containing the default values
-- @return the destination table, `dst`
function M.setdefaults(dst, src) return M.update(dst, src, true) end
--- copy a varable.
-- If `var` is a table, then the table is cloned, otherwise return the value
-- of `var`.
-- @param var the variable to copy
-- @return a clone of `var`
function M.copy(var)
return type(var) == 'table' and M.setdefaults({}, var) or var
end
--- extend an array.
-- inserts all elements in `src` into `dst`
-- @param dst the destination array
-- @param src the source array
-- @return the destination array, `dst`
function M.extend(dst, src)
for _, v in ipairs(src) do table.insert(dst, v) end
return dst
end
--- extract the keys of a table as an array.
-- @param tbl a table
-- @return an array of keys
function M.keys(tbl)
local res = {}
for k, v in pairs(tbl) do table.insert(res, k) end
return res
end
--- determine whether a value is present in an array.
-- @param list an array
-- @param value a value
-- @return a boolean
function M.contains(list, value)
for k, v in ipairs(list) do if v == value then return true end end
return false
end
--- map a function over a table.
-- @param func a function with one argument
-- @param tbl the table
-- @return the transformed table
function M.map(func, tbl)
local res = {}
for k, v in pairs(tbl) do res[k] = func(v) end
return res
end
--- select array values satisfying a filter.
-- @param func a function with one argument
-- @param list the array
-- @return the filtered array
function M.filter(func, list)
local res = {}
for _, v in ipairs(list) do if func(v) then table.insert(res, v) end end
return res
end
return M
|