works:programmer:lua:cache-class

Класс кеширования данных для LUA

-- wow time() func analog   (epochTime sec)
function time()
    return os.time(os.date("!*t")) 
end
 
 
function CacheClass()
    local storage = {}
    local pack, unpack = table.pack, table.unpack
    return function(key, timeout, callback, ...)
        local now = time()
        if storage[key] ~= nil and storage[key][1] > now then
            return unpack(storage[key][2])
        end
        local value = pack(callback(...))
        storage[key] = { now + timeout , value }
        return unpack(value)
    end
end
 
 
-- function(key, timeoutSec, updatefunc)
Cached = CacheClass()
 
 
aa,ab,ac = Cached("debounce5sec", 5, function(a, b, c)
    -- this shall executed
    return 2 * a, 2 * b, 2 * c
end, 2, 4, 16)
print(aa,ab,ac)
 
 
aa,ab,ac = Cached("debounce5sec", 5, function(a, b, c)
    -- this will executed only if 5 sec passed
    return 4 * a, 4 * b, 4 * c
end, 2, 4, 16)
print(aa,ab,ac)
works/programmer/lua/cache-class.txt · Last modified: 2022/01/27 06:38 by Chugreev Eugene