self is a keyword referencing the class or table itself
consider this example:
local teapots = {}
teapots.__index = teapots
function teapots:ReturnMyName()
print(self.Name)
end
function teapots.new(Name : string)
local init = {
Name = Name
}
return setmetatable(init,teapots)
end
local Teapot = teapots.new("Billy")
Teapot:ReturnMyName()
> "Billy"
you can only get self when you call a function with the colon
local mytable = {'red', 'blue'}
local together = ''
for i, data in pairs(mytable) do
together = together.. mytable[i] .. ', '
end)
together = '{' .. together .. '}'
Well. Self is a reference to what the function was called on. It’s a bit hard to explain so let’s take an example
local t
t = {}
t.number = 5
function t.addNumber(table, n)
table.number = table.number + n
print(table.number)
end
So here we have a table t that has a number and the function addNumber. AddNumber expects to get a table like t as the input so it can add to table.number. Well we have t. Let’s just throw t into that function.
t.addNumber(t, 5)
And now it should change t.number to 10 and print it. But, it’s kind of annoying to have to type t in as the first parameter. So instead let’s use colon notation. This line is exactly the same as what we just did above.
t:addNumber(5)
Colon basically just passes the thing it’s called on as the first value.
Now let’s rewrite the addNumber function to use colon notation. Or Better yet, I’ll change the “table” parameter to self, then right colon notation underneath.
function t.addNumber(self, n)
self.number = self.number + n
print(self.number)
end
function t:addNumber(n)
self.number = self.number + n
print(self.number)
end
So these 2 functions are identical. : when declaring a function just secretly passes in self as a parameter so you don’t have to do it with dot notation.