English What does self do?

2 replies
Goto Page
To the start Previous 1 Next To the start
08.03.20 11:28:17 pm
Up
The kennyS
User
Offline Off
Hello again, I came up with another lua scripting question, What does self do? What it is used for? Also, Can you show an example of it, please?
09.03.20 01:15:15 am
Up
Reaper
User
Offline Off
www.cs2d.me has launched - Join Now *CLOSED*
09.03.20 11:32:03 am
Up
TrialAndError
User
Online On
Okay, so "self" is actually just a syntactic sugar.

Instead of always having to do this:

Code:
1
2
3
4
5
6
7
8
9
local obj = {
     variable = 3,
     
     method = function(self, whatever)
          self.variable = 5
     end
}

obj.method(obj, ...)


Where, "obj" is a table, "method" is a function within that table and "variable" is some property within that table. If you wanted to get hold of the "variable" value, you couldn't do "obj.variable" because the table hasn't been initialized yet.

So, you can see that we pass "obj" to the method as the first parameter so that the function knows what to operate on. As you can see, it's gets annoying to always pass in the obj as the first parameter. So the people at Lua made a syntactic sugar for that which is the ':' that you often see.

Code:
1
obj:method(...)


Under the hood, lua will pass "obj" as the first parameter and you don't have to worry about that.

Now the second annoying thing is to always write the "self" in the arguments when you declare the function. That's why declaring functions with ':' also exists, which puts a hidden "self" as the first argument.

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
local obj = {
     variable = 5
}

function obj:method(--[[Hidden Self Here]] whatever)
     self.variable = 5
end

obj:method(--[[Hidden obj here]] ...)


--What all that means is just

function obj.method(self, whatever)
     self.variable = 5
end

obj.method(obj, ...)
edited 1×, last 09.03.20 12:03:23 pm
To the start Previous 1 Next To the start