util.cache: Add support for creating a proxy table to a cache, that looks and acts (mostly) like a normal table. No tests yet.
authorMatthew Wild <mwild1@gmail.com>
Sun, 22 May 2016 18:18:23 +0100
changeset 7438 8603b16e85c7
parent 7436 7eec6f3c7300
child 7441 6bf4c227c8f3
child 7442 4cccaa33b0a1
util.cache: Add support for creating a proxy table to a cache, that looks and acts (mostly) like a normal table. No tests yet.
util/cache.lua
--- a/util/cache.lua	Sun May 22 14:39:14 2016 +0200
+++ b/util/cache.lua	Sun May 22 18:18:23 2016 +0100
@@ -116,6 +116,28 @@
 	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);