blob: 2ae15ee989cd589bc35894346ca602a5ca79657a (
plain)
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
|
---@class QuarrelTable
local qtable = {}
--- Map a function on each element in the table
---@param t table
---@generic T
---@param f fun(v: T): T
---@return table
function qtable.map(t, f)
local nt = {}
for k, v in pairs(t) do
nt[k] = f(v)
end
return nt
end
--- Filter a table with a function
---@param t table
---@param f fun(v: any): boolean
---@param dict boolean Whether the supplied table is a dictionary
---@return table
function qtable.filter(t, f, dict)
local nt = {}
for k, v in pairs(t) do
if not f(v) then
goto continue
end
if dict then
nt[k] = v
else
table.insert(nt, v)
end
::continue::
end
return nt
end
-- This is taken from http://lua-users.org/wiki/SortedIteration
-- This version is stripped of comments and empty lines + some stuff is renamed
local function __gen_oindex(t)
local oindex = {}
for key in pairs(t) do
table.insert(oindex, key)
end
table.sort(oindex)
return oindex
end
function qtable.onext(t, state)
local key = nil
if state == nil then
t.__oindex = __gen_oindex(t)
key = t.__oindex[1]
else
for i = 1, #t.__oindex do
if t.__oindex[i] == state then
key = t.__oindex[i + 1]
end
end
end
if key then
return key, t[key]
end
t.__oindex = nil
end
function qtable.opairs(t)
return qtable.onext, t, nil
end
return qtable
|