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.
Is there a better way to do this? Is this insanely stupid from a style/maintainability standpoint?
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.