So really where I am coming from is java where you would be able to get the parent class by using the super keyword but in lua there doesn’t seem to really be any way to get the parent class without getting a recursion error.
I found this post which I thought could help me but I was really confused looking at it.
For a metatable class, you would need to store the superclass within the class itself:
local vehicle = Vehicle.new("Ship")
--[[
Something like this:
function Vehicle.new(vtype: string)
local baseClass = BaseClass.new() -- create the base class within the constructor
local class = setmetatable({
super = baseClass, -- assign it here as the super class
Type = vtype
...
}, VehicleMetatable)
return class
end
--]]
print(vehicle.super) --> <BaseClass>
For a Roblox class, there’s no method (without manually assignment super/subclasses in one table). Lua/Luau doesn’t have native ‘classes,’ so there’s no proper functionality for something like fetching a superclass
It’s best to treat Lua “classes” and “objects” as a python dictionary/java hashmap that can store functions, data types, etc. Inheritance in Lua essentially creates a table of the parent class and overrides over some dictionary keys with the child class.
Like what @HugeCoolboy2007 said, you’ll have to create a key/entry to point to the original method of the parent class. You can chain them like a single linked list if you’d like.
Assuming you want to fetch all the superclasses of an instance, you can take advantage of the IsA operator, that returns true if an instance is either that class or a subclass of the class passed in:
--replace this with a list of all Roblox classes
local allClasses = {"LuaSourceContainer", "LocalScript", "Instance"}
local function getSuperclassesOf(object: Instance): {string}
local superclasses = {}
for _, class in pairs(allClasses) do
if not object:IsA(class) then continue end
if object.ClassName == class then continue end
table.insert(superclasses, class)
end
return superclasses
end
--should print LuaSourceContainer, Instance
print(table.concat(getSuperclassesOf(script), ", "))
Although for this method to work you need to have an up-to-date list of all the Roblox classes as a table of strings and also it will return all superclasses as strings, not just the parent superclass. If you want information regarding which superclass is a direct superclass of the instance you need to use more sophisticated methods on top of this. For example for each superclass you can check if the other found superclasses are superclasses of it, and you can consider the one with the maximum superclasses the one directly above your class. This sounds easy to implement but is actually harder than it sounds, because IsA relies on instances to work, and we can’t create an instance of every super class(for example we can’t Instance.new a LuaSourceContainer). For this problem specifically you need to implement many tricks and special cases, if you want to take it a bit further.