App patterns · real, tested code

Cache Values with an LRU Cache in Larzscript

Cache expensive results with a bounded, least-recently-used eviction policy, plus one-line memoization for a whole function.

cache.set()/get() take an optional per-entry TTL; cache.memoize() wraps a single-argument function so repeat calls skip recomputation automatically, and cache.stats() reports real hit/miss counts.

larzscript pkg install cache

Code

import "cache" as cache

let c = cache.new(100)
cache.set(c, "a", 1, 60)
print(cache.get(c, "a", nil))
print(cache.get(c, "missing", "default"))

let memo = cache.memoize(fn(n) { return n * n })
print(memo["call"](5))
print(memo["call"](5))
print(cache.stats(memo["cache"]))
Output
1
default
25
25
{hits: 1, misses: 0, size: 1, capacity: 1000}