Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

"self" is unless? What is self!?

Asked by 5 years ago
Edited 5 years ago

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

2 answers

Log in to vote
0
Answered by
royaltoe 5144 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago

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.

0
STOP YOU ARE SO SMART YOU GOT 300 REP IN 2 hours DUDe!!! ;( greatneil80 2647 — 5y
0
i'm not smart i'm just wasting too much time here. royaltoe 5144 — 5y
Ad
Log in to vote
0
Answered by
Sulfone 141
5 years ago

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:

  1. It makes it more obvious that it's for a method.
  2. It's consistent with method definition sugar syntax.
  3. It's short and doesn't require thinking of a new parameter name.

Answer this question