As I understand from docs, we don't have classes in Lua. Lua does not have the concept of class; each object defines its own behavior and has a shape of its own.
So a simple emulation of classes in Lua, following the lead from prototype-based languages, such as Self and NewtonScript would be something like.
function Account:new (o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
What I don't understand here is what does o = o
do and why do we need to use setmetadatatable and the next line index = self
.
What does it do and why do we need them?
Also self.o = o
was pretty much understood, but o = o
, wouldn't that create any conflict?
For the first line, see Vlads answer.
setmetatable(o, self)
assigns self
as the metatable of o
. self
can now contain a set of metamethods to add functionality to o
(see link for more information).
__index
is the metamethod called when o
does not contain an indexed key. It can also be another table. In this example, __index
is set to self
, so if you attempt to index a nil value in o
, it will look in self
instead. If you only call Account:new()
, self
is Account
.
Example from you link: you have an deposit function in Account
. After you created your object o = Account:new()
you can now call o:deposit()
. This will look in o
for deposit, fails, then looks in __index=Account
for deposit
, succeeds, calls it.
If you do not set the metatable, or __index
, calling o:deposit()
will result in an attempt to call a nil value
.