What does self.<inset something here> do?

In a lot of LUA scripts I see… self.<something>.

what does self do exactly?

Give me an example in a script. Maybe its a var named “something”, maybe its to keep people like you to keep creating threads like this.

function ENT:PhysicsCollide( data, physobj )      

// Play sound on bounce    
if (data.Speed > 50 && data.DeltaTime > 0.2 ) then        
         self.Entity:EmitSound( "Rubber.BulletImpact" )     

// Bounce like a crazy bitch     
local LastSpeed = data.OurOldVelocity:Length()    
 local NewVelocity = physobj:GetVelocity()       

local TargetVelocity = NewVelocity * LastSpeed * 0.99       

physobj:SetVelocity( TargetVelocity )  


What is the purpose of self?

It return ENT.

I wanna give my self a bad reading…

Used in entities and meta tables to define a player or the entity.


[lua]local meta = _R.Player

function meta.SetDollars( self, n )
n = tonumber( n )
if !n then return end
n = math.floor( n )

self.Dollars = n
SaveDollars( self )


Above is incorrect. It’s method used in all tables to pass the table itself into a function in the table.

[lua]local what = {}

function what:Stuff(arg1)


function what.Stuff(what , arg1)


They’re exactly the same.

(Following on from flapjack’s post)

Using a colon : instead of a period . is like having an invisible “self” variable that refers to the parent table:

local cake = {}
cake.tasty = true

function cake:IsTasty()
return self.tasty

function cake.IsTasty2( self )
return self.tasty

cake:IsTasty() --Returns true (there is an invisible self variable here because we called it with a :, self = cake)
cake:IsTasty2() --This is the same as cake.IsTasty2( cake )

function cake.IsTasty3()
return self.tasty
cake:IsTasty3() --This will error because self doesn’t exist

Calling cake:IsTasty() is exactly the same as calling cake.IsTasty( cake ).
self is automatically defined

Hopefully that was helpful and not just some retarded gobbledegook I spat out

Flap is wrong they’re not both the same. One defines ‘what’ and another defines ‘self’

[lua]local tbl = {}

function tbl:foo()
print( self )

function tbl.foo2( self )
print( self )

– All the same result:
tbl.foo( tbl )
tbl.foo2( tbl )[/lua]

Different variable name, same value.