So I was learning everything I could find about metatables
and got at a moment stuck. I asked myself some questions.
For example let’s look at this code that declares a metatable
, and with it, I initialize some functions.
local metatable = {}
metatable.__index = metatable
function metatable.new()
local self = setmetatable({}, metatable)
return self
end
function metatable.printHello(self, string) -- As you can see I'm using only the dot -> .
print(self, string)
end
local t = metatable.new()
t:printHello("Hello") -- prints "{} Hello"
The output is specified in the code ^
But what if at line 10 I put 2 dots instead of 1?
Result:
local metatable = {}
metatable.__index = metatable
function metatable.new()
local self = setmetatable({}, metatable)
return self
end
function metatable:printHello(self, string) -- As you can see I'm using only the 2 dots -> .
print(self, string)
end
local t = metatable.new()
t:printHello("Hello") -- prints "Hello nil"
And also for some reason it highlights me the self
parameter at line 10 with orange line. Why?
Here are the combinations for line 10 and 14:
- dot and 2 dots → “{} Hello”
- dot and dot → “Hello nil”
- two dots and two dots → “Hello nil”
4.two dots and dot → “nil nil”
I want to know what these “dot” specifiers mean in classes and what are the results. And also why for combination 3 and 4 it highlights with orange line the self
parameter.