Whats a self?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
SuperMeijin
Prole
Posts: 15
Joined: Wed Oct 03, 2012 3:37 pm

Whats a self?

Post by SuperMeijin »

Whats a self or self table i heard about it and have no idea what it is and cant find any information on it? :ultrahappy: :ultrahappy: :ultrahappy:
LuaWeaver
Party member
Posts: 183
Joined: Wed Mar 02, 2011 11:15 pm
Location: Ohio, USA

Re: Whats a self?

Post by LuaWeaver »

Well, it comes into play when using methods. Let's say we have this code:

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)
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.
"your actions cause me to infer your ego is the size of three houses" -finley
User avatar
Saegor
Party member
Posts: 119
Joined: Thu Nov 08, 2012 9:26 am
Location: Charleroi

Re: Whats a self?

Post by Saegor »

anthor explaination :

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
so a colon is : inplicitly passing self (aka the parent table) as first argument of a function
Current work : Isömap
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: Whats a self?

Post by Robin »

So, in recap: the colon and self are syntactic sugar.

Code: Select all

function sometable:somefunc(...)
end
is the same as

Code: Select all

function sometable.somefunc(self, ...)
end
And

Code: Select all

sometable:somefunc(...)
is the same as

Code: Select all

sometable.somefunc(sometable, ...)
No more, no less.

Useful, because it can greatly reduce typing in some cases.
Help us help you: attach a .love.
User avatar
Azhukar
Party member
Posts: 478
Joined: Fri Oct 26, 2012 11:54 am

Re: Whats a self?

Post by Azhukar »

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")
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot] and 8 guests