I made this metatables wrapper for object oriented programming. I thought I’d take advantage of __add here, but I’m curious about how it’ll affect performance.
Here’s an example of how to extend the pre-existing “car” class:
lambo = new_class {
fuel = 50,
speed = 100,
explode = function(self)
self.fuel = 0
self.speed = 0
self.accelerate = function() end
end
} + car
Will this disable all Luau optimizations?
Also, is there a way to dynamically create Luau types?
Here’s the full code:
function new_class(classConstructorTable)
classConstructorTable.__index = classConstructorTable
classConstructorTable.new = function(newObjVals)
return setmetatable(if newObjVals then table.clone(newObjVals) else {}, classConstructorTable)
end
return setmetatable(classConstructorTable, {
__add = function(tab,extensionClassConstructorTable)
local extendedObj = extensionClassConstructorTable.new()
setmetatable(classConstructorTable,extensionClassConstructorTable)
return classConstructorTable
end
})
end
--------------------------------------
car = new_class {
fuel = 100,
speed = 0,
accelerate = function(self)
self.speed += 10
self.fuel -= 1
end
}
lambo = new_class {
fuel = 50,
explode = function(self)
self.fuel = 0
self.speed = 0
self.accelerate = function() end
end
} + car
local automobile = car.new()
automobile:accelerate()
local fancyCar = lambo.new({ speed = 123 })
fancyCar:accelerate()
print("automobile fuel: ",automobile.fuel)
print("automobile speed: ",automobile.speed)
print("fancyCar fuel: ",fancyCar.fuel)
print("fancyCar speed: ",fancyCar.speed)
print'BOOM'
fancyCar:explode()
fancyCar:accelerate()
print("automobile fuel: ",automobile.fuel)
print("automobile speed: ",automobile.speed)
print("fancyCar fuel: ",fancyCar.fuel)
print("fancyCar speed: ",fancyCar.speed)