-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhelpers.lua
More file actions
72 lines (55 loc) · 1.42 KB
/
helpers.lua
File metadata and controls
72 lines (55 loc) · 1.42 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
-- Any copyright is dedicated to the Public Domain.
-- https://creativecommons.org/publicdomain/zero/1.0/
-- collection of helpers for lua scripts
local helpers = {}
--- Clears any table of its contents, without breaking existing references. Returns input for convenience.
--- @param tab table
--- @return table
function helpers.clear_table(tab)
for key in next, tab do
rawset(tab, key, nil)
end
return tab
end
--- Gets keys in ascending order
--- @generic T
--- @param tab table<integer, T>
--- @return integer[]
function helpers.sorted_keys(tab)
local keys = {}
for x in pairs(tab) do
table.insert(keys, x)
end
table.sort(keys)
return keys
end
--- Like pairs but in ascending key order
--- @generic T
--- @param tab table<integer, T>
--- @return fun(): (integer, T)|nil
function helpers.sorted_pairs(tab)
local keys = helpers.sorted_keys(tab)
local idx = 1
local my_next = function()
local key = keys[idx]
idx = idx + 1
if key ~= nil then
return key, tab[key]
end
return nil
end
return my_next
end
-- join list of strings with sep
function helpers.join(sep, string_list)
if #string_list > 0 then
local message = string_list[1]
for i = 2, #string_list do
message = message .. sep .. string_list[i]
end
return message
else
return nil
end
end
return helpers