I have the impression that "self" is useless. I do not understand his meaning and I am curious!
This wiki page is empty of information. Methods
local testButton = { enabled = true, imageActivated = "rbxgameasset://Images/ImageButtonActivated", imageNormal = "rbxgameasset://Images/ImageButtonNormal", changeEnabled = function(self) self.enabled = not self.enabled end } testButton:changeEnabled()
In this example if I change "self" to anything its worked too.
So why "self" and what is it? And how to I CAN use it!
Im originally french sorry for my mistake
hey,,,, self isn't unless!
I just wrote an answer about it the other day: https://scriptinghelpers.org/questions/87145/about-the-keyword-self-how-it-works-its-uses-and-whats-so-useful-about-it#80712
It can be a bit abstract so if you need more explanation, let me know.
It's correct that self
there can be changed to any name and still works - it's just a parameter name. It's not really a keyword.
To start explaining why it's often named self
instead of something like the object type, lets consider another way to define the function: outside the table constructor.
function testButton.testEnabled(self) self.enabled = not self.enabled end
Here we could change self
to anything other parameter name. However Lua provides a shorter way of writing the that section (method definition sugar syntax):
function testButton:testEnabled() self.enabled = not self.enabled end
This is equivalent to the first section. It has a first parameter named self
, but it's just hidden. And that's really all that self
is in Lua. I like this quote about it:
self is not a keyword. It's not magical. It's not managed by the language. It's just the name of the first argument passed to your function.
But why do people often still use self
as the first parameter name in the 1st case, or the case you found? Here are three upsides to it:
- It makes it more obvious that it's for a method.
- It's consistent with method definition sugar syntax.
- It's short and doesn't require thinking of a new parameter name.