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" )     
end       

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

NewVelocity:Normalize()    
local TargetVelocity = NewVelocity * LastSpeed * 0.99       

physobj:SetVelocity( TargetVelocity )  

end


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.

[editline]01:42PM[/editline]

[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 )

end
[/lua]

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)

end

function what.Stuff(what , arg1)

end[/lua]

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:

[lua]
local cake = {}
cake.tasty = true

function cake:IsTasty()
return self.tasty
end

function cake.IsTasty2( self )
return self.tasty
end

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
end
cake:IsTasty3() --This will error because self doesn’t exist
[/lua]

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 )
end

function tbl.foo2( self )
print( self )
end

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

Different variable name, same value.