Will Luau optimizations still work with this? Are dynamic Luau types a thing?

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)

AFAIK having metatables will not disable optimizations, but your implementation will be slighter slower than the normal OOP idiom because you’re cloning and creating new functions each time you call it.

I wrote a tutorial about how to TypeCheck with the general OOP idiom, however the method I describe there is not very user-friendly but does support inheritance. If you don’t need classes to inherit, I recommend this idiom instead.

As for dynamic types, there are these things called generics that allow you to pass types in functions and tables, however I don’t think they are going to be helpful in your case since you’re going to be injecting the new function in your wrapper anyways.

2 Likes