Can someone tell me how i can use self in this scenario?

i wanted to start using self, but to be honest i don’t even know how i can take use of it in my scenario, so i’m going to ask on here

scenario is you have an enemy and i want to check if that enemy has a death animation, a wandering state etc.


okay so, inside a server script in serverscriptservice, there is a “damage” function that also checks for kill, if kill is true, then run a function that plays a death animation if the enemy has one

it looks something like this

local module = require(module)

local function CheckForKill(humanoid)
   if humanoid.Health < 1 then
      module:OnDeath()
   end
end


local function DealDamage() -- this gets called whenever it's needed
   -- pretend there's code that deals damage here
   CheckForKill(enemyHumanoid) -- pretend this parameter exists okay
end

and inside the module script there’s something like this:

function module:OnDeath()
   if self:FindFirstChild("DeathAnimation") then
     -- play animation
   end
end
-- would this work???

I’M REALLY CONFUSED ON HOW SELF WORKS SORRY IF THIS IS A STUPID POST :sob:

this is what self does

local Vector = Vector3.new(5,5)

print(Vector:Dot(Vector3.new(5,5))) -- passed Vector as Self automatically 
print(Vector.Dot(Vector, Vector3.new(5,5)))

when you use a function with : it will pass the variable before it which is called Vector in this case as self

you donot have to use : here since you donot need to get the module
this is another example

module:OnDeath()

is the same as doing

module.OnDeath(module)

in the OnDeath function self will be equal to module and module doesnot have a DeathAnimation so it willnot work self is used in other cases you donot need to use self for that function

1 Like

self is a keyword variable that is automatically assigned when calling methods inside tables with the colon : operator.

local foo = {key = true}

function foo:bar()
    print(self.key) -- true (from the original foo table)
end

foo:bar()
-- equivalent to
foo.bar(foo)

You’ll mainly see it used with OOP. If you want to learn OOP, there are a lot of topics and tutorials available with a simple search.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.