-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcaseless-table.lua
59 lines (54 loc) · 1.41 KB
/
caseless-table.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
local API = {}
local wvmt = { __mode = 'v' }
---@param weakValue? boolean
---@return table<string, any>
function API.create(weakValue)
---@type table<string, any>
local lowerMap = {}
if weakValue then
setmetatable(lowerMap, wvmt)
end
---@type table<string, string>
local upperKeyMap = {}
local out = {}
local function nextKV(t, k)
if t ~= lowerMap then
error('invalid table')
end
if k then
k = string.lower(k)
end
local nextK, nextV = next(lowerMap, k)
if not nextK then
return nil
end
local upperK = upperKeyMap[nextK]
return upperK, nextV
end
setmetatable(out, {
__newindex = function (t, k, v)
local lk = string.lower(k)
lowerMap[lk] = v
if v == nil then
upperKeyMap[lk] = nil
return
elseif not upperKeyMap[lk] then
upperKeyMap[lk] = k
end
end,
__index = function (t, k)
local lk = string.lower(k)
local v = lowerMap[lk]
if v == nil then
upperKeyMap[lk] = nil
end
return v
end,
__pairs = function ()
---@diagnostic disable-next-line: redundant-return-value
return nextKV, lowerMap, nil
end,
})
return out
end
return API