In OOP, its not necessary call a constructor with a :
, like Module:new()
.
When using the :
indexer, it calls the function while passing the table it exists on (in a metatable, it passes the main table instead).
local Table = {}
Table.a = 1
function Table:GetA()
return self.a
end
In this code, I made a simple table with a value and a function where the function takes self
.
local a1 = Table:GetA()
This code will return the value of index a
properly, no errors.
local a2 = Table.GetA() -- errors
But calling it like this makes an error: attempt to index nil with 'a'
or in lua demo attempt to index a nil value (local 'self')
. What happened? Why is it nil? Well, since I called the function with a .
, it did not pass a self
table. This actually means that you can call it with a .
and pass a different self
table.
local differentTable = {}
local a3 = Table.GetA(differentTable)
Although this won’t error, the code tries to index a blank table with a
, which is a nil value.
Going back to the constructor thingy, calling it with a :
returns Module
. Here is the problem with your solution: doing it like this, actually makes a new index (or overwrite) an index in the class itself instead of the object.
local Module = {}
Module.__index = Module
function Module:new()
self.a = 1
self.b = 15
return setmetatable(self, Module)
end
This will create an index a
and b
in the module, not the object. Thus, printing the table will result in:
{
["new"] = "function",
["AddAToB"] = "function",
["DoSomthing"] = "function",
["a"] = 1,
["b"] = 15
}
There are two values in the Module
table which should not exist.
If you followed the lua guide, for some reason, the guide uses a :
indexer to call the constructor class which is weird, but it creates a new object o
, unlike just using the self
table.