So I’m kind of new to object oriented programming and I’m trying this library, and I’m trying to make it so that the Ferrari inherits stuff from the NewCar constructor but when I try to print out the price it errors.
function NewCar(name,dealer)
return {
name = name or "DefaultCar";
dealer = dealer or "DefaultDealer";
GetName = function(self)
return self.name
end;
GetDealer = function(self)
return self.dealer
end;
}
end
function NewFerrari(name, dealer,price)
local ferrari = NewCar(name,dealer)
price = price or 100
ferrari.CheckPrice = function(self)
return self.price
end
end
local SportsCar = NewFerrari("Marc's Ferrari", "Marc's Automotive!", 500)
print(SportsCar.CheckPrice())
Well, not really I’m using NewCar as a base constructor to make the Ferrari and Im trying to add my own functions to it, that are just for the Ferrari subclass of newcar
Because you’re not defining ferrari.price which .CheckPrice is trying to return. Therefore the error occurs in the function because it tries to index a nil value.
Have you tried printing self to see if self returns anything? It should return a table.
But yes, you still need to return ferrari in the end of your function.
Example:
function NewFerrari(name, dealer,price)
local ferrari = NewCar(name,dealer)
ferrari.price = price or 100
ferrari.CheckPrice = function(self)
return self.price
end
return ferrari
end
function NewCar(name,dealer)
return {
name = name or "DefaultCar";
dealer = dealer or "DefaultDealer";
GetName = function(self)
return self.name
end;
GetDealer = function(self)
return self.dealer
end;
}
end
function NewFerrari(name, dealer,price)
local ferrari = NewCar(name,dealer)
ferrari.price = price or 100
ferrari.CheckPrice = function(self)
return self.price
end
return ferrari
end
local SportsCar = NewFerrari("Marc's Ferrari", "Marc's Automotive!", 500)
print(SportsCar:CheckPrice())
This code works perfectly fine for me as long as you didn’t take what I mentioned previously for granted as they also were important notes to get this to work.
I see you already have your answer solved, but since you’re new to OOP I would recommend reading this for a cleaner way of what you’re doing and for a better understanding of OOP overall