Whats a self?
Posted: Thu Nov 29, 2012 8:56 pm
Whats a self or self table i heard about it and have no idea what it is and cant find any information on it?
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)
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
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, ...)
Code: Select all
local function myfunction(test,something)
print(test,something)
end
local mytable = {
f = myfunction,
}
mytable:f("123")