I made a module that lets you make classes in luau
Here it is
class.rbxm (1.7 KB)
Example: (ChatGPT generated the examples for me because I am too lazy)
local new, class, extends = require(module)()
class "Person" {
constructor = function()
this.name = "Unknown"
this.age = 0
print("Person created: " .. this.name .. ", Age: " .. this.age)
end,
greet = function()
print("Hello, my name is " .. this.name)
end
}
local john = new(Person)()
john.name = "John"
john.age = 30
john:greet() -- Should print: "Hello, my name is John"
class "Employee" [extends "Person"] {
constructor = function()
super()
this.jobTitle = "Unknown"
print("Employee created: " .. this.name .. ", Job Title: " .. this.jobTitle)
end,
work = function()
print("I am working as a " .. this.jobTitle)
end
}
local jane = new(Employee)()
jane.name = "Jane"
jane.age = 28
jane.jobTitle = "Engineer"
jane:greet() -- Should print: "Hello, my name is Jane"
jane:work() -- Should print: "I am working as a Engineer"
local original = {
name = "Original",
details = {
age = 25,
profession = "Developer"
}
}
class "Vehicle" {
constructor = function()
this.brand = "Unknown"
this.model = "Unknown"
print("Vehicle created: " .. this.brand .. " " .. this.model)
end,
drive = function()
print("Driving a " .. this.brand .. " " .. this.model)
end
}
class "Car" [extends "Vehicle"] {
constructor = function()
super()
this.numDoors = 4
print("Car with " .. this.numDoors .. " doors created.")
end,
honk = function()
print("Honk! Honk!")
end
}
local myCar = new(Car)()
myCar.brand = "Toyota"
myCar.model = "Corolla"
myCar.numDoors = 4
myCar:drive() -- Should print: "Driving a Toyota Corolla"
myCar:honk() -- Should print: "Honk! Honk!"
To use it you do
local new, class, extends = require(module)()
with new you can do
new(class)(…)
or
new “class”(…)
There is also ‘super’ and ‘this’ but it will show as “not defined” cause it is only defined in constructors
Feedback will be appreciated