Hello!
I am wondering if it is possible for a custom object I created to inherit the methods of a Roblox instance. For example, if I make a class called “EnhancedPart”, which is essentially a normal Roblox part with some additional functionality, is it possible for me to call part’s :GetMass()
method on the instantiated version of “EnhancedPart”?
Before you all yell at me, yes, I am aware that the number of apparent use cases of such a design are quite limited. I am also aware that there are a number of workarounds that work completely fine, such as assigning the instance to its own field in the object or creating homebrewed methods that implement the instance’s methods within the object, but I want to know if it’s possible to achieve exactly what I’ve stated above. This is more out of curiosity than anything else.
I have been able to create a design that allows me to read the fields/properties of an instance. Here it is so far:
--ModuleScript (EnhancedPart class)
local ePart = {}
function ePart.new()
local self = setmetatable({}, ePart) --Sets self's metatable to ePart class
ePart.__index = ePart --Look through ePart if no such field/method exists in self
local part = Instance.new("Part", workspace) --New part!
local secondTable = {} --A metatable for ePart
local partTable = setmetatable(ePart, secondTable) --Set it
secondTable.__index = part --Look through part's data if no such field/method exists
return self
end
return ePart
--Script (just used for testing of EnhancedPart)
local ePart = require(script.Parent.EnhancedPart)
local p1 = ePart.new()
print(p1.Transparency) --prints 0
print(p1:GetMass()) --Throws an error
Here is the error I’m receiving:
As you can see, p1.Transparency
prints out fine. Calling the method, however, yields an error. I don’t understand why it assumes I’m using a ‘.’ instead of a “:”. My guess is that something about my assigning secondTable.__index
to a part is throwing everything off.
Another potential solution that I have stumbled across while researching is to retrieve a direct table of the instance’s properties and methods via HTTP requests, but I really don’t want to do that. I want to know if there is a plausible method to inherit all of an instance’s properties via metatable/metamethod magic.
Again, I understand that this seems intuitively useless because there are a number of workarounds that work just fine, such as assigning the object’s field to the instance. There is something just so clean about the thought of being able to call my custom object with inherited methods from an instance.