Hi all, apologies if this has been asked before, but say I have an OOP class; how do I make the attributes private? At the moment they can be accessed by the script that instantiates them - and this doesn’t follow ‘encapsulate what varies’ does it?
Unfortunately, lua doesn’t have a very good option to make private variables. There are ways to do so, don’t get me wrong, but it isn’t practical in this sense as it takes up too much time and doesn’t really have a reason in this scenario. This isn’t really a problem though, as the real reason private variables are “private” is mostly to prevent bugs.
Essentially:
What I recommend you do is to name any variable you think should only be used in that class with an underscore before it. It’s what most of the developers I know do.
local Class = {}
local ClassMT = {__index = Class}
local privates = {}
function Class.New(...)
local self = setmetatable({}, ClassMT)
privates[self] = {}
self:Initialize(...)
return self
end
function Class:Initialize(...)
privates[self].MyPrivateMember = "shh secret"
end
return Class
If the class is defined in a ModuleScript, there’s no way for outside scripts to access privates.