1
1
--- Table with metamethods to track the number of items inside of a table including KV pairs.
2
2
local KVCounter = {}
3
3
4
+ -- Helper function to implement next on KVCounter.
5
+ -- There is no metamethod to do this but is useful for getting a value without knowing the keys.
6
+ local function kv_counter_next (t , index )
7
+ local mt = getmetatable (t )
8
+ return next (mt .inner , index )
9
+ end
10
+
4
11
local function kv_counter_index (t , k )
5
12
local mt = getmetatable (t )
13
+
14
+ if k == " next" then
15
+ return kv_counter_next
16
+ end
17
+
6
18
return mt .inner [k ]
7
19
end
8
20
9
- local function kv_coutner_newindex (t , k , v )
21
+ local function kv_counter_newindex (t , k , v )
22
+ assert (k ~= " first" , " next is an unallowed key in KVCounter" )
23
+
10
24
local mt = getmetatable (t )
11
25
local existed = mt .inner [k ] ~= nil
12
26
if existed and v == nil then
@@ -31,7 +45,7 @@ local function kv_counter_factory()
31
45
local mt = {
32
46
-- Avoid blowing up lua closures by defining these outside of the function.
33
47
__index = kv_counter_index ,
34
- __newindex = kv_coutner_newindex ,
48
+ __newindex = kv_counter_newindex ,
35
49
__pairs = kv_counter_pairs ,
36
50
__len = kv_counter_len ,
37
51
count = 0 ,
0 commit comments