What does self do?

Hello, what I want to achieve is what is self and what it does?

self

I’ve tried finding videos and still can’t find a video

I’ve tried looking in the API reference and couldn’t find anything

If you could, please let me know what it is, what it is used for,and give an example if you can

2 Likes

self is basically the table itself, when you are calling methods in it.

This is a simple example

local tbl = {}

function tbl:foo()
    print(self)
end

function tbl.bar()
    print(self)
end

function tbl.baz(self) -- it can be named anything
    print(self)
end

tbl:foo() -- table
tbl:bar() -- nil

tbl:baz() -- table
tbl.baz() -- nil

Thanks for the little explanation, I’m still gonna find more answers to get a good understanding

It’s used in OOP (Object Oriented Programming) to define itself in a Method:

function Module:GetName()
print(self)
-- This is the same as
function Module.GetName(self)
print(self)

Hate seeing needlessly complex examples of how its used, in practice you’ll be using it as such:

local module = {}

function module.Example(Argument)
   self --Does not exist here, you'd have to define self in a function like this
end 

function module:Example2(Argument) 
   self --Exists here, represents the first argument
end

--[[
   The defining difference is where or not the function name is appended with . or :
   The common name for functions in modules or tables that use : is a "method."
   While a function with . Is just a normal function. If you want to learn more,
   head to https://www.lua.org/pil/16.html
]]

return module

1 Like