Auto-complete problem with inheritance

I have a problem where when I create a class and inherit from that class, then I create a member of the inheritor class it only has the methods of the ancestor class in its autocomplete.

For example:

local Animal = {}
Animal.__index = Animal

Animal.Sound = ""
function Animal:MakeSound()
	print(self.Sound)
end

function Animal.New(sound)
	local self = {}
	setmetatable(self, Animal)
	self.Sound = sound
	return self
end

local Cat = {}
Cat.__index = Cat
setmetatable(Cat, Animal)

function Cat.New(name)
	local self = Animal.New("meow")
	setmetatable(self, Cat)
	self.Name = name
	return self
end

function Cat:PrintName()
	print(self.Name)
end

local Jossie = Cat.New("Jossie")
Jossie:PrintName()

When I type Jossie:... it only has the following options:

изображение

When it should also have the method Cat:PrintName()

I don’t understand if I am doing something wrong and if I am doing something wrong, I would like to ask for some help on that.

However, if it’s just the way roblox works, then is there a possible way to go around that, because it wouldn’t be nice to type the name of every method I need.

This is probably due to how metamethods work on roblox and lua in general. I dont think there is a way to fix this.

1 Like

I understand, though it would be nice if roblox and luau devs decided to fix this.

However, do you think there might be workaround?

I have digged around but couldn’t find a workaround for this. The best you can do is define the functions on the Animal metatable or scrap metatables all together.

I know a way to do this, but it is not ideal.

You can create a type for your class and then include all of the methods.
Like this:

local Cat = {}
Cat.__index = Cat
setmetatable(Cat, Animal)

type CatType = {
	PrintName : (self) -> (),
	MakeSound : (self) -> ()
}

function Cat.New(name) : CatType
	local self = Animal.New("meow")
	setmetatable(self, Cat)
	self.Name = name
	return self
end

function Cat:PrintName()
	print(self.Name)
end

local Jossie = Cat.New("Jossie")
Jossie:MakeSound()
Jossie:PrintName()
1 Like

The only way would be to use a union type

type Animal = typeof(setmetatable({} :: {
    -- properties go here
}, {} :: { __index: {
    -- methods go here
}})

-- ...

type Cat = typeof(setmetatable({
    -- cat properties go here
}, {} :: { __index: {
    -- cat methods go here
}}) | Animal

local cat = Cat.new() :: Cat
1 Like

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