yet another class implementation-if you hate getters/setters

Showcase your libraries, tools and other projects that help your fellow love users.
Post Reply
gestaltist
Prole
Posts: 49
Joined: Thu May 29, 2014 10:56 am

yet another class implementation-if you hate getters/setters

Post by gestaltist »

Hi everyone. I have been using kikito’s excellent middleclass library for my projects but I have noticed a few things:
- I never use inheritance so I don’t really need it
- I don’t like to use explicit getters and setters - I would like to use the normal syntax and have getters/setters be hidden (example below)
- I like to define objects via tables - it makes it easy to abstract class/object definitions to a separate file.

So I decided to write my own implementation and I would like to share the first result. No .love file as it doesn’t use Love2D for anything - just pure Lua:
https://github.com/stefanstr/class-by-gestaltist

I would like to hear from you if anyone else finds this approach useful and if you have any improvement suggestions.

Code: Select all

--Example code
class=require”class”
Vector=class{
name=“Vector”;
obligatory={“x”, “y”};
getters={length=function(t) return (t.x^2 + t.y^2)^0.5 end};
readonly={“length”} -- length shouldn’t be set directly as it is always recalculated - you can define “readonly” fields that cannot be changed after object initialization.
}
v1=Vector{x=1; y=1} -- if you try to initialize an object without the obligatory fields, you will get an error message
print(v1.length) -- will output the correct value of 1.4142...
print(v1.class) -- will output “Vector”
v1.class = “whatever” -- will throw an error as  “class” is a readonly field by default.
gestaltist
Prole
Posts: 49
Joined: Thu May 29, 2014 10:56 am

Re: yet another class implementation-if you hate getters/set

Post by gestaltist »

I have added a lot of stuff to this, based on my personal needs, as none of you have commented:
- the possibility to name allowed keys and/or allowed key types (for example, you might only want numeric keys plus an “id” key)
- methods
- the possibility to define getters and setters for a whole key type (e.g., a setter that will get invoked for every numeric key and make sure it is an integer before assigning a value) - the setters are still hidden so this: “t[1] = 3” will actually invoke a setter if there is one
- debug functions to print all the values of an instance and the metafields

I have one last thing on my roadmap, which is a little more challenging: I want to add the possibility to define hidden setters/getters for nested keys (i.e., for something like t[1][1]).

Nobody has commented so far so I don’t even know how many of you find this useful (I can see one person has starred the repo but I cannot see how many people actually played with it).

I would be grateful for any comments/suggestions.
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 2 guests