Forum

> > CS2D > Scripts > What does self do?
ForenübersichtCS2D-Übersicht Scripts-ÜbersichtEinloggen, um zu antworten

Englisch What does self do?

2 Antworten
Zum Anfang Vorherige 1 Nächste Zum Anfang

alt What does self do?

The Dark Shadow
User Off Offline

Zitieren
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?

alt Re: What does self do?

TrialAndError
User Off Offline

Zitieren
Okay, so "self" is actually just a syntactic sugar.

Instead of always having to do this:

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.

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.

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, ...)
1× editiert, zuletzt 09.03.20 12:03:23
Zum Anfang Vorherige 1 Nächste Zum Anfang
Einloggen, um zu antworten Scripts-ÜbersichtCS2D-ÜbersichtForenübersicht