Hello all. Trying to implement a LRU cache with Luau typing in a ModuleScript, and here’s what I’ve got so far:
--!strict
local LRUCache: LRUCacheImpl = {} :: LRUCacheImpl
LRUCache.__index = LRUCache
type map<K, V> = {[K]: V}
type LRUCacheImpl = {
__index: LRUCacheImpl,
new: (max_size: number) -> LRUCache -- Recursive type being used with different parameters
}
export type LRUCache<K, V> = typeof(setmetatable({} :: { max_size: number, map: map<K, V> }, {} :: LRUCacheImpl))
function LRUCache.new<K, V>(max_size: number)
local __LRUCache = setmetatable({}, LRUCache)
__LRUCache.max_size = max_size
local __map: map<K, V> = {}
__LRUCache.map = __map
return __LRUCache
end
return LRUCache
I’m trying to create a cache that will cache values in the form of {[K]: V} as denoted by the map type I’ve defined; however, this throws an error when I try something like this:
From my understanding, all should be well here; what is the issue? It seems like there is something I’m not understanding properly, and the official Luau documentation w.r.t metatables is… rough, to say it kindly
"Recursive type being used with different parameters" disappears whenever I delete the generic typings. Is this currently supported in Luau to begin with? The beta solver gives me a whole host of separate issues so if that’s the solution I’ll just deal with a typeless LRU cache.
EDIT: From what I’ve gleamed in RFCs and whatnot it seems like this is not currently supported under concerns of exponential explosion when dealing with potential recursive generic types, at least to my knowledge. Ah well! If anyone has any solutions or ideas please feel free to respond.
I might be missing something but LRUCache isn’t a type, right? What is being returned should be a type and not a reference to a table. At the very least, you can do something like this
I intended LRUCache to be a type defined with two generics that would be the key-value pair in whatever internal storage mechanism I decide to run with. My issue is that it won’t let me define LRUCache<K, V> due to recursion issues. Without the generic types, it is recognized as its own type just fine
P.S. I’m following the official Luau typing guide for OOP/meta-tables, so everything type-related to a metatable is pulled from here
Whoops, I am very blind lol. Based on the error, my guess is that it’s complaining that LRUCache has generic types but you don’t specify those types in LRUCacheImpl. I’m not sure if this is the “correct” way of doing things but you can fix it by turning LRUCacheImpl into a generic type as well.