- 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.