util.cache: Add support for creating a proxy table to a cache, that looks and acts...
authorMatthew Wild <mwild1@gmail.com>
Sun, 22 May 2016 17:18:23 +0000 (18:18 +0100)
committerMatthew Wild <mwild1@gmail.com>
Sun, 22 May 2016 17:18:23 +0000 (18:18 +0100)
util/cache.lua

index 54f3e10b175055a85696dcbf5fc5040ad2d00028..44bbfe3098427ae9c9fef7ba9b6ce8d9a4830ddf 100644 (file)
@@ -116,6 +116,28 @@ function cache_methods:tail()
        return tail.key, tail.value;
 end
 
+function cache_methods:table()
+       if not self.proxy_table then
+               self.proxy_table = setmetatable({}, {
+                       __index = function (t, k)
+                               return self:get(k);
+                       end;
+                       __newindex = function (t, k, v)
+                               if not self:set(k, v) then
+                                       error("failed to insert key into cache - full");
+                               end
+                       end;
+                       __pairs = function (t)
+                               return self:items();
+                       end;
+                       __len = function (t)
+                               return self:count();
+                       end;
+               });
+       end
+       return self.proxy_table;
+end
+
 local function new(size, on_evict)
        size = assert(tonumber(size), "cache size must be a number");
        size = math.floor(size);