One important thing to remember is that Moon nay is object-oriented. There are no classes themselves.
Lua works more like Javascript’s "object orientation" (older versions of it, at least), where you would move the ". prototype" of the object.
But Lua is flexible to the point of being able to "simulate" object orientation with some of its constructions.
You can start by setting your "class" (which, remember, is an object. There are no classes).
local Quadrado = {}
Quadrado.__index = Quadrado
The first row simply creates an empty table. Then we will put some attributes and methods in it. The important thing here is the second row. The __index
passes all the indexes (Classe[x]
, Classe.x
) to the table itself. This will make sense in the next block of code.
Now, let’s define a builder:
function Quadrado:novoQuadrado(tamanhoLado)
return setmetatable({lado = tamanhoLado}, Quadrado)
end
The magic is done in the setmetatable
. Note that I am returning a new table with an attribute side ({lado = tamanhoLado}
, and passing my definition of Squared like his metatable.
One metatable is a way to change the behavior of a table. A good example of this is to define two tables, a
and b
, and try to add them up a + b
. Lua doesn’t know how to do this, but she will look at these table metatables. If any of them have a method in the index __add
, Lua will use this method to make the sum (something like a:__add(b)
).
Remember the __index
that we changed up there? It’s the same scheme. We’re sending our Square to look for indexes in the Square itself. When we use a Quadrado.area
, which we will define shortly, Lua will look for this index (or attribute, or field) in the table Quadrado
, and find Quadrado.area
. Doesn’t that make sense? But remember we passed the square as a metatable? Then all the objects we create will use Square as metatable, and will search for their indexing in the same way (Quadrado.area
). I don’t know if you understand what I mean :(
To define a method, we can use the following syntax:
function Quadrado:area()
return self.lado * self.lado
end
That syntax Quadrado:area
it’s just syntatic sugar for
function Quadrado.area(self)
Now just use our "class":
local q = Quadrado:novoQuadrado(10)
print(q:area()) -- 100
The q:area
is syntatic sugar for q.area(q)
(remember that we changed the metatable? This is using the area of the Square). I still don’t know if I can understand, but this is it.
So, answering your questions:
- No, there is no constructor, because there is no class. What exists is the function we agree to as constructor (
Quadrado:novoQuadrado
).
- The method is declared with the change in the metatable.
- It is important to note that we are using two "objects" (two tables,
Quadrado
and q
), and not a class and an object.
Of course, it’s been a long time since I’ve studied the Moon, and I don’t know if there are any developments in this scheme. But in my day.
So that’s where I saw this method
:new
– Wallace Maxters