Skip to content

Instantly share code, notes, and snippets.

@cloudwu
Last active July 30, 2024 06:35
Show Gist options
  • Save cloudwu/e7184c8860fd8ff993828a67338ed87a to your computer and use it in GitHub Desktop.
Save cloudwu/e7184c8860fd8ff993828a67338ed87a to your computer and use it in GitHub Desktop.
cache function result with key
-- https://weibo.com/2050899237/OpPODpfBK
local function cache_func(func, cap)
cap = cap or 128
local current_cache = {}
local cache_meta = { __index = current_cache }
local func_meta = { __index = nil }
local prev_meta = { __index = nil }
local n = 0
local function renew_cache()
prev_meta.__index = setmetatable(current_cache, func_meta)
current_cache = setmetatable({}, prev_meta)
cache_meta.__index = current_cache
end
renew_cache()
function func_meta:__index(key)
n = n + 1
if n > cap then
renew_cache()
n = 0
end
local v = func(key)
current_cache[key] = v
return v
end
return setmetatable({}, cache_meta)
end
--- test
local cache = cache_func(function(key)
return "key:" .. tostring(key)
end)
for i = 1, 256 do
print(cache[i])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment