Immutable properties for objects

I’m attempting to find the best way to create immutable properties for objects. Here is what I have so far:

local Class = { };
Class.__index = Class;

local names = { };

function Class.GetName(self)
	return names[self];
end;

function Class.Dispose(self)
	names[self] = nil;
end;

function Class.new(name)
	local class = setmetatable({ }, Class);
	names[class] = name;

	return class;
end;

local bob = Class.new('Bob');
print(bob:GetName());
bob:Dispose();

I have two questions here:

  1. Are there any detriments (short or long term) to what I’m doing here?
  2. Is there a better way to go about this?
1 Like

using __newindex is meant to be useful for this purpose.
If you make a function such that it always returns a new copy of the data stored, when access is attempted though __newindex.

Sorry, I don’t exactly understand where you’re coming from here. Maybe my choice of wording in my OP was poor, so that’s my bad.

I’m looking to create an immutable private property for an object; one that should only be accessed through it’s Getter function and not through any metamethods & cannot be set to any other value after the object’s initialization.

If this explanation doesn’t change your answer, I’d love if you provided me with an example. I’m a visual learner

Using the __newindex method would remove the need for getters. Metatable allow for custom programming in such broad ways, there are so many ways you could use them.

I’d be tempted to use it with weak tables to provide a place to store the immutable data. Here’s an example:

example.lua (1.4 KB)

(although it’s worth noting metatable can be overwritten with getraw and setraw, there’s lots of ways to go about doing what you want to do - this is just a nice way which avoids the need for getters/setters which can become quite clunky if there are too many. You could extend the __newindex function to allow indexes of specific names to be set into the data table.)

1 Like

Thank you for taking the time to make the example, now I see what you’re doing here. While this doesn’t solve the use-case I originally had in mind, I can certainly use this down the road. I like your use of weak tables here, I had forgotten about those