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()
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()
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.
yes because modules have to return something. My code was a very very basic example of how self works.
why wouldn’t you just print the table
Fair enough. I also just found this link that pretty much can explain what "self"
is.
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.
this guy taught me self in one post while you guys kept arguing
That’s because they’re all … selfish
Badumtss
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.