Page 1 of 1

Whats a self?

Posted: Thu Nov 29, 2012 8:56 pm
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:

Re: Whats a self?

Posted: Fri Nov 30, 2012 12:41 am
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.

Re: Whats a self?

Posted: Fri Nov 30, 2012 6:50 am
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

Re: Whats a self?

Posted: Fri Nov 30, 2012 8:04 am
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.

Re: Whats a self?

Posted: Fri Nov 30, 2012 10:17 am
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")