Whats a self?
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
-
- Prole
- Posts: 15
- Joined: Wed Oct 03, 2012 3:37 pm
Whats a self?
Whats a self or self table i heard about it and have no idea what it is and cant find any information on it?
Re: Whats a self?
Well, it comes into play when using methods. Let's say we have this code:
If you notice, the numbers in "q" change. This is because when I use a colon, it "implies" the self argument, which is the table the function (method) is in. Thus, a self table is the table the function (method) is in.
For more information, you can read PiL.
Code: Select all
coords={x=0, y=0}
function coords:slide(x,y)
self.x=self.x+x
self.y=self.y+y
end
function coords:new()
local newTab={}
return setmetatable(newTab, {__index=coords})
end
local q=coords:new()
print(q.x,q.y)
q:slide(5,0)
print(q.x,q.y)
For more information, you can read PiL.
"your actions cause me to infer your ego is the size of three houses" -finley
Re: Whats a self?
anthor explaination :
so a colon is : inplicitly passing self (aka the parent table) as first argument of a function
Code: Select all
-- if you declare :
blabla = {}
blabla.x = 40
blabla.y = 60
-- and if you create the move() function inside de table
blabla.move(x, y)
blabla.x = blabla.x + 20
blabla.y = blabla.y + 30
-- you can, for reuse of the function later, type this
blabla.move(self, x, y)
self.x = self.y + 20
self.y = self.y + 20
-- or this, that's the same !
blabla:move(x, y)
self.x = self.x + 20
self.y = self.y + 20
Current work : Isömap
- Robin
- The Omniscient
- Posts: 6506
- Joined: Fri Feb 20, 2009 4:29 pm
- Location: The Netherlands
- Contact:
Re: Whats a self?
So, in recap: the colon and self are syntactic sugar.
is the same as
And
is the same as
No more, no less.
Useful, because it can greatly reduce typing in some cases.
Code: Select all
function sometable:somefunc(...)
end
Code: Select all
function sometable.somefunc(self, ...)
end
Code: Select all
sometable:somefunc(...)
Code: Select all
sometable.somefunc(sometable, ...)
Useful, because it can greatly reduce typing in some cases.
Help us help you: attach a .love.
Re: Whats a self?
You can even rename "self" to something else.
Code: Select all
local function myfunction(test,something)
print(test,something)
end
local mytable = {
f = myfunction,
}
mytable:f("123")
Who is online
Users browsing this forum: Ahrefs [Bot], Bing [Bot] and 8 guests