Get Metatable (Class) from Instance

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

Any help would be appreciated!

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
1 Like

Wouldn’t that be inefficent the more ores I instantiate?

Depends on how much ores and how often you are calling get, but in a standard game environment, the performance is negligible.

1 Like

I can confirm it will not be standard :sob:, kind of a minecraft amount of ores. (infinite until a certain high limit, depending on how far your willing to go)

Thanks alot though. I will try it right now.

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.

1 Like

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

2 Likes

I will try that. Thank you so much.
Not really sure what that is, however

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

1 Like

Essentially changing it to this, where the key is your ore:

function Ore.new(oreFolder, oreName)
    -- code
    Stored[ore] = self
end

function Ore.Get(ore)
    return Stored[ore]
end
1 Like

Ohhh my bad. Thanks.

aso[dkada;kdaaaaasddas

Thanks for the example.

asdasdadasd

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.