OOP Private Variables

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?

currently I just do
thisClass.thisAttribute = 123

2 Likes

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.

Here is an example of what I mean

-- public variables
thisClass.AtrributeValue = 42

-- private variables
thisClass._thisAttribute = 123

You can remember this fairly easily once you get used to it.

1 Like

Thank you for replying. Is this just a visual peace-of-mind kind of thing, as in for me to understand that it’s supposed to be private?

Here’s how I usually do it:

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.

15 Likes

Yes, that’s the main reason: the developer should know that this is a private variable and shouldn’t be accesed from outside of a class.

1 Like

This is perfect, thank you very much.

This is so clever!! THANK YOU!