Object setters and getters with dot notation

Instead of using getters and setters like

Object:SetFoo(1)
Object:GetFoo()

I want to be able to use dot notation

Object.Foo = 1
Object.Foo

because my client is more familiar with that. This is the solution I’ve come up with:

local Object = {} do
	Object.__index = function(object, key)
		if Object.Fields[key] and Object.Getters[key] then
			return Object.Getters[key](object)
		end
	end
	Object.__newindex = function(object, key, value)
		if Object.Fields[key] and Object.Setters[key] then
			Object.Setters[key](object, value)
		end
	end
end

Object.Fields = {
	Foo = "",
	Bar = ""
}

Object.Getters = {
	Foo = function(self)
		return self._foo
	end,
	Bar = function(self)
		return self._bar
	end
}

Object.Setters = {
	Foo = function(self, foo)
		self._foo = foo
	end,
	Bar = function(self, bar)
		self._bar = bar
	end
}

function Object.new(foo, bar)
	return setmetatable({
		_foo = foo,
		_bar = bar
	}, Object)
end

return Object

It also collapses quite nicely.
image
Is there a better way to do this? Is this insanely stupid from a style/maintainability standpoint?

2 Likes

What’s preventing you from just initializing the fields directly in the class constructor?

The setters for my actual use case have custom functionality.

I would say this is fine if your client would like it more but I would suggest that the other way is better for performance and is less code overall

1 Like

No, this is a good solution, and is standard practice in Python. There’s not much of a benefit to the Java styled “Object:GetName()” convention. The only downside here is that you’re potentially hiding the performance complexity of a get or set (if you have to perform 10,000 table accesses, it should be clear that this is what’s going on with an explicit function call), but in most cases, like “Object.Name” returning first name concatenated with last name, this isn’t an issue.

My only suggestion is that you don’t need to use “empty” setters and getters for each attribute.

That’s a great suggestion! Empty getters/setters create clutter, but I always use them to keep consistency. Instead, I could simply set/return the value if there’s no getter/setter.

Checkout this post:

I think it will be beneficial for you.

1 Like