Ways to make editable and uneditable OOP class properties?

How can you make self (a table) return properties but some of them can really be editable? The module user would be able to modify the public properties but if they try modifying the private table (frozen) it would error.

Example:

local Class = {}

function Class.new() 
 local self = setmetatable({}, Class) 

self.Private = {}
self.Public = {}

table.freeze(self.Private) 

self.Public.Number = 1 -- Editable by user
self.Private.Number = 0 -- Not editable

 return self
end

return Class

What’s the issue with this?

Well, attempting to edit the properties via methods won’t work since the table is frozen so how do i go about fixing this?

The goal is that there’s properties the user can edit but some that the user cannot edit only readable but the uneditable ones can be edited but only by the module itself. For example, something like Class.Intitized shouldn’t be able to be editable by the user as the module depends on it for error handing like if the user uses a method but the module is initialized so it’ll error.

Edit: This belongs to this category because it will spark a discussion and its not entirely a “help me figure fix this bug” or what not

1 Like

#help-and-feedback:scripting-support

You can store private properties outside of the object, but this would be messy. Prefix private properties with _ to indicate it shouldn’t be changed by the user of the module. It can still be changed, this is just a convention.

2 Likes

You can make private variables outside of the class.

local private = {}
local class = {}

however, this is only suitable if it is a singleton.

I want it so the properties are read-only not hidden completely. Like if i had ismoving i would want to know if the object is moving but not modify it

__index Programming in Lua : 13.4.1
__newindex Programming in Lua : 13.4.2
You can use these to change how keys are accessed and set in a table.

You can set a metamethod called __index to prevent that, but they can always rawget and rawset it.

Would it show the properties and still make then unable to be edited

Yes, you can read from them but not write to them, but why would you need to do that anyways?

Im creating a module for my friends because they’re new scripting and i wanted to help them out with some stuff so i thought of creating a module. The reason for this post is that they’ll try to maybe modify important properties the module needs to operate like for example: Is Loaded, Is Initialized are variables you don’t want a user to change. What’s the purpose for these in my module? Well, for example, if they use a method without using the Init method it will warn or if they use Init method without providing the necessary parameters it will error.