I’m having trouble “hooking” a class to an instance in Roblox OOP. I have an “Ore” class that’s constructor takes oreFolder: Folder (with ore parts) and oreName: string (name of the ore to retrieve). I need to access the ore’s class during mining, but I can’t attach metatables as attributes or children to the ores. How can I do this?
local Ore = {}
Ore.__index = Ore
function Ore.Create(
oreFolder: Folder,
oreName: string
): self
local self = setmetatable({}, Ore)
--
self.Name = oreName
self.Instance = oreFolder:FindFirstChild(oreName):Clone()
-- Hooking code would probably be here?
--
return self
end
return Ore
You would have to start storing your classes in one table (making sure to unreference upon destroying) and creating a getter function.
function Ore.Get(ore)
for _, class in Stored do
if class.Instance == ore then
return class
end
end
end
local ore = Ore.Get(workspace.SomeOre)
local oreMetatable = if ore ~= nil then getmetatable(ore) else nil
I can confirm it will not be standard , kind of a minecraft amount of ores. (infinite until a certain high limit, depending on how far your willing to go)
Then do your entire functionality in one script. If you’re looking to reference the ore somewhere else (i.e. tools), you will still have to do a table search to get its class anyways unless you start incorporating attributes where you don’t have to do a search.
you can use the O(1) lookup property of a dictionary by storing key value pairs in a table, where the ore instance is the key and the value is the class, and when you want to get the class of an ore instance you just index the dictionary with the ore instance. This will not become less efficient with more ores
basically if you store the values like
local x = {[instance]=class…}
and you index the table like x[instance]
its more efficient than iterating over a table and checking for its class