Repository navigation
Expand file tree
/
Copy pathutil.lua
More file actions
112 lines (96 loc) · 2.23 KB
/
Copy pathutil.lua
File metadata and controls
112 lines (96 loc) · 2.23 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
---@diagnostic disable: deprecated
local util = {}
util.unpack = table.unpack or unpack
function util.eval_with_env(filepath, env)
local chunk
if _VERSION == 'Lua 5.1' then
local fn, err = loadfile(filepath)
if fn then
chunk = setfenv(fn, env)
else
error(err)
end
else
local fn, err = loadfile(filepath, nil, env)
if fn then
chunk = fn
else
error(err)
end
end
return chunk()
end
function util.log(msg, level, scope)
level = level or 'info'
local prefix = level
if scope then
prefix = prefix .. '(' .. scope .. ')'
end
prefix = prefix .. ':'
print(prefix, msg)
end
-- make a read-only view of a table
function util.freeze(tbl)
local proxy = {}
return setmetatable(proxy, {
__index = tbl,
__newindex = function (_, _, _)
error('attempt to modify read-only table')
end,
__pairs = function()
return pairs(tbl)
end,
__ipairs = function()
return ipairs(tbl)
end,
__len = function()
return #tbl
end
})
end
-- return a shallow copy of a table
function util.shallow_copy(tbl)
local mt = getmetatable(tbl)
local res = {}
for k, v in pairs(tbl) do
res[k] = v
end
return setmetatable(res, mt)
end
local function spairs_iter(tbl, k)
local v
repeat
k, v = next(tbl, k)
until type(k) == 'string' or k == nil
return k, v
end
-- iterate over only pairs with string keys
function util.spairs(tbl)
return spairs_iter, tbl, nil
end
-- deeply merge two tables, returning a new table. does not mutate originals
---> for string keys, if both values are plain tables (no metatable), recursively merge
---> for integer keys, child values are appended after parent values
function util.deep_merge(parent, child)
-- not a plain table (or nil), child overrides
if type(parent) ~= 'table' or getmetatable(parent)
or type(child) ~= 'table' or getmetatable(child) then
return child
end
local result = {}
for k, v in pairs(parent) do
result[k] = v
end
for k, v in pairs(child) do
if type(k) == 'number' and math.floor(k) == k then
result[#result + 1] = v
elseif type(result[k]) == 'table' and type(v) == 'table'
and not getmetatable(result[k]) and not getmetatable(v) then
result[k] = util.deep_merge(result[k], v)
else
result[k] = v
end
end
return result
end
return util