Luau type inheritance? (OOP)

I’m trying to get better at using Luau features.
Is there currently a way to have a type inherit another type?

Let’s say I have a parent class like this:

type Animal = { Age: number, Health: number, Position: Vector3, __index: any, new: any}

local AnimalClass : Animal = {
	Age = 1, 
	Health = 100, 
	Position = Vector3.new(0,0,0), 
	
	new = nil, 
	__index = nil, 
}
AnimalClass.new = function()
	local newAnimal = {}
	setmetatable(newAnimal,AnimalClass)
	return newAnimal
end
AnimalClass.__index = AnimalClass

How’d I make a type/class that extends this Animal type/class?

This tutorial should help

that’s Lua
I’m trying to do this using Luau features

luau is for the most part, just a sandbox version of lua. As far as I know, roblox hasn’t changed tables and metatables That being said, oop can be made in exactly the same way.

Luau introduces types though, which helps the intelesense in Studio’s script editor. I know how to use metatables, I’m trying to use types.

1 Like

While luau introduces types, you still have to define the data that these types hold, it does not fill this data in for you, it’s simply a way for Lua to have types for not only readability, but for Lua to optimize around these types. If you are making an object using LuaU you still have to initialize these variables manually and/or set a metatable on the object. Though when it comes to inheriting from types I’m uncertain if you would it has the capibility of inheriting such because of that.

EDIT: Seems like you can using the & operator to join two types.

1 Like

so it’s not possible to do this
that sucks
I hope it’s a planned feature they have coming out soon :sob:

By Luau “Type Inheritence”, I’m assuming you’re looking for a way to derivate types instead of making entire new types from scratch, and not so much about the metatable inheritance.

Luau provides intersection types using the & operator that can be used to join together two non-primitive user-defined table types.

So in the context of your AnimalClass, you can do this:

type Animal = { Age: number, Health: number, Position: Vector3, __index: any, new: any}

type Dog = Animal&{Bark:()->()}

To get a “subtype” Dog, which will also have the attributes of type Animal.

26 Likes

Oh wow, I didn’t know this, I should probably get into luau some more, thanks for the information! :smiley:

This is one big chunk of what I wanted.
I probably should’ve mentioned I’m using !strict, and I wanna use metatables to instantiate objects with default values/functions.

It seems using !strict will cause the editor to yell at you when using metatables to make objects. It seems I can’t have my cake and eat it too. Either way, I guess this is technically the solution to the question I asked.

1 Like