Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

"self" is unless? What is self!?

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

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.