Forum
CS2D Scripts What does self do?What does self do?
2 replies 1
Instead of always having to do this:
1
2
3
4
5
6
7
8
9
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
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
1