-
Notifications
You must be signed in to change notification settings - Fork 0
/
lens.lua
43 lines (37 loc) · 1010 Bytes
/
lens.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
---@class Lens
---A lens is a bijective table, a table where if `t[a] -> b` then `t[b] -> a`.
local Lens = require("ji/class")("Lens")
function Lens:new(table)
local lens = { data = {} }
setmetatable(lens, self)
if table then
for key, value in pairs(table) do
lens[key] = value
end
end
return lens
end
function Lens:clear()
rawset(self, "data", {})
end
function Lens:__index(key)
return rawget(self, "data")[key]
end
function Lens:__newindex(key, value)
local previousvalue = rawget(self, "data")[key]
if previousvalue ~= nil then
rawget(self, "data")[previousvalue] = nil
end
rawget(self, "data")[key] = value
if value ~= nil then
local previouskey = rawget(self, "data")[value]
if previouskey ~= nil then
rawget(self, "data")[previouskey] = nil
end
rawget(self, "data")[value] = key
end
end
function Lens:__pairs()
return pairs(rawget(self, "data"))
end
return Lens