BaseClass - Class Inheritance Made Easy(ier)

What Is BaseClass?

BaseClass is a lightweight module script that helps developers organize classes in the Explorer window, automatically managing metatables. It also serves as the root for all other classes.

Basic Usage

Before using any library, you must first require() it.

local new = require(game.ServerStorage.BaseClass)

:warning: Avoid using require() on individual class modules, as they will not be properly initialized.

Classes are organized under the main module, and you can access them with a simple lookup. To create an object, simply call the class you want to instantiate.

local obj = new.Animal.Dog("Rover")

The returned object is now ready for use.

Creating Classes

A class is defined by the table returned from a module script, with inheritance determined by its parent.

Here’s an example of how it would look in the Explorer window:

structure

Most classes will have a constructor, along with various properties and methods associated with them.

Below is an example of a basic class:

local Animal = {
	Name = "Animal";
}

function Animal:new(name)
	self.Name = name
end

function Animal:Eat()
	print(self.Name, "is eating")
end

return Animal

Extending Functionality

By inheriting from a parent class, the subclass gains access to its properties and methods, allowing you to extend or override functionality.

The following demonstrates how to access members of a class’s parent:

local super = require(script.Parent)

function Class:Method()
	super.Method(self)
end

:warning: Remember that the first parameter must be self, and note the use of a period (.) instead of a colon (:).

If you don’t manually call a base method, its behavior will be completely overridden.

In Conslusion

You should now have enough knowledge to start creating your own classes.

Have fun and enjoy!

2 Likes

Why is the constructor defined as a method and not a static function

This is because the actual constructor, found in BaseClass as __call, creates a new object, sets the metatable, and passes it along to new. If it didn’t, you wouldn’t have a reference to self.

1 Like

So it’s kinda like an extension to the actual constructor which can modify it

I suppose so. It’s just setting up the object so you call methods and assign properties from within new.

1 Like