Car = {}
Car.__index = Car
function Car.new(position, driver, model)
local newcar = {}
setmetatable(newcar, Car)
newcar.Position = position
newcar.Driver = driver
newcar.Model = model
return newcar
end
function Car:Boost()
self.Speed = self.Speed + 5
end
newcar = Car.new(Vector3.new(1,0,1), "Guest1892", game.ReplicatedStorage.F1Car)
newcar:Boost()
can somebody please explain what is going on here?
(literally just try to explain it the best way you can) i dont mind if it is a thousand characters long
When you do function Car.new, you are setting Car.new to a function. When you do the newcar, you set it’s meta table to Car so it can have the same functions. Since newcar is also a table, you can set anything like it’s a property, even if it’s not a model. So, when you do newcar:Boost(), it searches the newcar table for boost. It doesn’t find it. Then, it searches it’s meta table, Car, and it finds the Boost function. It sets Speed in the table of newcar to it’s Speed plus 5.
When you are running the Car.new() function, it accepts these three arguments in the exact order they were put in: position,driver,model. When they called the function, they set the position to a random Vector3 value. Then, they made a string defining the player who is drving the cars name, and then they link the model the car is. They then return the newcar table they just made so it’s table can be used as a variable to use it’s functions.
Of course, that was just an example. OOP is usually just used so you can have the same functions without having to paste them through every script you need them in. OOP also is used in ModuleScripts which can run on the Client or the Server depending on what required it. OOP is just a efficient way to run functions.