What does "self" do?

you shouldn’t be defining self as a variable, it is automatically passed. For example:

local object = {
	Message = "Hi!"
}

function object:SayMessage()
	print(self.Message)
end

object:SayMessage()
1 Like

What are you trying to prove sir?

In order to print a table you could do this:

local mytable = {'red', 'blue'}

local together = ''

for i, data in pairs(mytable) do
    together = together.. mytable[i] .. ', '
end)

together = '{' .. together .. '}'

or horizon/vertical coding.

I mean yeah it works, but it throws an error at ya’.

yes because modules have to return something. My code was a very very basic example of how self works.

1 Like

why wouldn’t you just print the table

Fair enough. I also just found this link that pretty much can explain what "self" is.

2 Likes

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.

5 Likes

this guy taught me self in one post while you guys kept arguing

7 Likes

That’s because they’re all … selfish
Badumtss

6 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.