Hey, I'm trying my hand at Object Oriented programming. Compared to java, I'm really having a hard time making the members of an object private, and some functions public.
Here is my code. It is in a ModuleScript
local Pizza = {}
function Pizza.new(...)
return setmetatable({
Slices = 8;
Toppings = {...};
Cooked = false;
}, Pizza)
end
Pizza.__index = Pizza
function Pizza:eat(x)
if x ~= nil then
self.Slices = self.Slices - x;
else
self.Slices = self.Slices - 1;
end
end
function Pizza:addTopping(x)
table.insert(self.Toppings, x);
end
Pizza.__newindex = function()
error("Pizza object is private");
end
return Pizza
And this is what I use to test it
pepperoni = Pizza.new("Pepperoni");
print(pepperoni.Slices);
pepperoni.Slices = 2;
print(pepperoni.Slices);
pepperoni.cheese = 5;
Problem is, setting pepperoni.Slices will indeed change the value of Pepperoni.Slices. How in the world do I make the variable Slices private, so it can't be changed, and my data is protected?

2 comments
What do you mean by, 'make an objects' variable private', exactly?
often in some coding languages you can declare something private or public. This determines if the public or private item can be used by foreign scripts or objects that are implementing the object. Public gives access, while private does not