Usage of 'self' in a script

Before you reply, yes, there’s countless topics on self already but I’m left with unanswered questions, I’ve re-read over the topics and I understand the following statements (i think).

  • ‘self’ is passed as the first parameter when you define a module function using : instead of .
  • self is the object that you called the function on?

Some things I’m not too sure on:

‘self’ is a table, is there times where self is an instance and not a table? Will it always be a table? If so, does this heavily tie in with metatables? Is it just used for convenience rather than needed to pass the object as a parameter?

1 Like

Instance are userdata.
There are cases where self is userdata

local userdata = newproxy(true) --> fake C userdata
local meta = getmetatable(userdata)

meta.__index = meta

function meta:test()
  print(type(self))--> userdata
end

self does not tie heavily with metatable (usually only in OOP)

local modularprogramming = {}

function modularprogramming:test()
  print(self, self == modularprogramming) --> some memory address, true
end

The : operator is merely a syntax sugar, It is not a must.

game.Destroy(workspace.Part)

works.

1 Like

It should be noted that majority of methods on Roblox Instances should be called with a : otherwise it will throw an error.

Edit: I should clarify, using : would require you to not pass the Instance in the parameter. So if you call a method with ., you must pass the instance as well.

It will only throw an error if you did not pass self or passed irrelevant types.
There are some cases where calling it with . is much more concise and quick, not to mention that it just looks visually more appealing.
For example:

local OK, errorOrData = pcall(Datastore.GetAsync, Datastore, PlayerKey)

As opposed to

local OK, errorOrData = pcall(function()
  return Datastore:GetAsync(PlayerKey)
end)
1 Like