Probably this topic has been discussed many times, but I could not find a thread about it on the forums here. Hence creating a new one.
I'm currently implementing my own gui library, and have decided to use a class system with a full hierarchy of widgets (having started Lua through WoW addons, I took as inspiration the hierarchy described in http://wowprogramming.com/docs/widgets_hierarchy). Since I'm not an expert in anything, I just took the simple class implementation described in the Lua manual, and I basically copy-pasted the function defined here: https://www.lua.org/pil/16.3.html
I'm going to describe how I use it, and I would like to know if this is the right way, or if this is completely wrong and I should change what I'm doing. Basically properties of objects are "private", and I use methods like gets and sets in order to access them. I like this because I can check in the "set" method if everything is correct, and I like the get thing because it allow easy default value. However, it has been drawn to my attention that the way I'm doing this would be very bad in JavaScript. Of course, comparison is not reason, but maybe the way it works is similar in Lua, and in particular in LuaJIT, so I prefer to be prudent and ask it to you experts around here
So let's take an example with a Rectangle class. An object of that class would have properties width and height, and a method to compute the area of the rectangle. The Rectangle class is created via the createClass from the Lua manual, and here is how I do this.
Code: Select all
Rectangle = createClass()
function Rectangle:setWidth(w)
assert(type(w) == "nil" or (type(w) == "number" and w > 0), "Width must be a positive number or nil.")
self.width = w
end
function Rectangle:getWidth()
return self.width or 3 -- default width is 3
end
function Rectangle:setHeight(h)
assert(type(h) == "nil" or (type(h) == "number" and h > 0), "Height must be a positive number or nil.")
self.height = h
end
function Rectangle:getHeight(h)
return self.height or 2 -- default height is 2
end
function Rectangle:getArea()
return self:getWidth() * self:getHeight()
end
Code: Select all
r = Rectangle:new({})
r:setWidth(5)
print(r:getArea()) -- should be 10
Question is: is this ok, or is this very bad?
As a side question, I was also wondering if it would be a good idea to implement the widget hierarchy in C++ and then use it via FFI. As I've never touch to FFI, if you think it would be a better idea, could you reference me a good starting tutorial to do this?
Thank you very much for having taken the time to read me.
TLDR: what is good inheritance and class usage practice in Lua?