11--- Table with metamethods to track the number of items inside of a table including KV pairs.
22local KVCounter = {}
33
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+
411local function kv_counter_index (t , k )
512 local mt = getmetatable (t )
13+
14+ if k == " next" then
15+ return kv_counter_next
16+ end
17+
618 return mt .inner [k ]
719end
820
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+
1024 local mt = getmetatable (t )
1125 local existed = mt .inner [k ] ~= nil
1226 if existed and v == nil then
@@ -31,7 +45,7 @@ local function kv_counter_factory()
3145 local mt = {
3246 -- Avoid blowing up lua closures by defining these outside of the function.
3347 __index = kv_counter_index ,
34- __newindex = kv_coutner_newindex ,
48+ __newindex = kv_counter_newindex ,
3549 __pairs = kv_counter_pairs ,
3650 __len = kv_counter_len ,
3751 count = 0 ,
0 commit comments