How can self be useful?

Hi! I just wanted to know how self could be useful.

Here is something I made:

--Module
local module = {}

function module:PrintOut()
	print(self)
end

return module
-------------------------------------------------
local module = require(script.Parent.ModuleScript)

module:PrintOut()

But it literally just prints out table: 0x330a77ac92faf6a4

I know how self works, it takes the thing before the colon as argument.

Thanks!

So that when you are working with objects in a method, so you can refer to itself. Your example doesn’t show the usefulness of self, something like this better does.

local Pizza = { }
Pizza.__index = Pizza

function Pizza.new(flavor, slices)
    return setmetatable({ flavor = flavor, slices = slices }, Pizza)
end

function Pizza:Eat()
    if self.slices <= 0 then
        return
    end

    self.slices -= 1
end

return Pizza

Then in a non-module

local Pizza = require(path_to_pizza)

local p = Pizza.new("Pepperoni", 8)
p:Eat()

Since there is no way to get the object you are calling the method on with without self that is where self is useful so object method can refer to itself. That said if you are using self in a non-OOP context of course it won’t be useful to you.

2 Likes

Just adding on, you can learn the basics of OOP from this thread by @magnalite , it really helped me out too:

1 Like