Add rationale paragraph to Classy objects section.

This commit is contained in:
Gonzalo Delgado 2024-09-10 07:07:18 -03:00
parent b03a179931
commit b9e1de7e67

View File

@ -32,8 +32,14 @@ That being said, I do find *inspect* to be quite useful (I believe it should be
#+end_src
* Classy objects
I can't escape an object-oriented style, especially for games, not sure if this is a good or bad
thing though I'd love to make a game in a more functional style, but the code for games made with
LÖVE I read so far are all OO. I mainly need "classy objects" for inheritance, I find that to be a
great way to re-use code while providing a lot of flexibility.
Lua doesn't have classes, but it does have objects with prototype capabilities through their metatable property, which allow implementing something close to inheritance. Let's create a base ~Object~ "class" which allows inheritance.
Lua doesn't have classes though, but it does have objects with prototype capabilities through their
metatable property, which allow implementing something close to inheritance. Let's create a base
~Object~ "class" which allows inheritance.
~Object~ will have a ~new~ method which will create new instances. This is achieved by first setting ~Object~ as its own ~__index~ metamethod and then setting ~Object~ as the metatable of a new, empty Lua table. This has the effect of fields not present in the new table to be looked up in ~Object~ (mainly for looking up methods). All of that is encapsulated in an ~Object:new~ function:
#+begin_src lua :tangle object.lua
@ -155,7 +161,6 @@ Next, we'll define mathematical operations by extending Lua's metamethods, to ge
function Vector:__len() -- magnitude
return math.sqrt(self.x^2 + self.y^2)
end
#+end_src
#+begin_src lua :tangle vector.lua