What is self? What it does?

Hello! I’m a new member here. I’m just looking for clarification or to have someone explain to me what code self does. I tried looking at OOP and still couldn’t understand it.

1 Like

self is the name of an implied first argument to a function that is called with : instead of .

Part:FindFirstChild("ChildName")

internally becomes:

Instance.FindFirstChild(Part, "ChildName")

This simplification is possible because Instance is where the function FindFirstChild is defined, and Part, which is itself an Instance, is also the first argument. This syntax exists to make it clearer that FindFirstChild is both a member function of, and operating on, Part.

When you define your own functions as members of a table using a : this first argument (Part) is hidden and given the name self

local MyTable = {}
MyTable.Florp = 1000

function MyTable:GetFlorp()
	return self.Florp
end

print(MyTable:GetFlorp())

--Is the same as

print(MyTable.GetFlorp(MyTable))

Someone on SH pointed out that, even though Roblox likes to highlight self, it is not a Lua keyword. They probably did this because they have mistaken it for actual keywords in other languages that do similar things, such as this in Java and C#

1 Like

To put it simply, when declaring a function like this:

local test= {}
function test:testfunction() --note : and not .
      print(self)
end
test:testfunction()

Essentially what happens is that self will be passed as the first argument of the function and it will also be the table the function is on. You can think of it something like this:

local test = {}
function test.testfunction(self) --note : and not .
      print(self)
end
test.testfunction(test)
test:testfunction() --can still call like this

So essentially defining a function with : makes self the first argument, and calling a function with : passes the table that the function is in as the first argument.

This can be expanded to things like Data Stores when pcalling,

pcall(datastore.GetAsync, datastore, key) --we are passing datastore as first arg

Hope this was resourceful

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