What is self used for?

So I was expermenting with Luau and I created this script below:

type car = {speed:number, model:string, dimensions:number, safe:boolean}

local honda = {speed=42, model="civic", dimensions=43, safe=true}
local truck = {speed=34, model="mack", dimensions=58, safe=false}

local car = {}

function car:GetSpeed(self)
	self.speed = 40
	return self.speed
end

print(car:GetSpeed(honda))

The topic of my concern is the function. So self is highlighted, meaning its special, but to me its just looks like any old param. If I replace “self” with “foo” or “bar”. The same results will print out aka 40.

self is the first argument passed when relating to Object Oriented Programming

self is an implicit parameter that is passed when you use the : notation to call functions on tables.

so

a:b(...)

is sugar for

a.b(a, ...)

and

function a:b(...)

end

is sugar for

function a.b(self, ...)

end

The implicit parameter doesn’t have to be called self though, and when using : you don’t pass it in yourself.

So if I do that function,

function car:GetSpeed()
	self.speed = 40
	return self.speed
end

So what I am getting is that no parameter = self?

function car:GetSpeed() is the same as function car.GetSpeed(self).

It is implicit.

So the above code will work right? ^ ^ ^

Test it, and you will see

tl;dr yes

Quick unrelated question: Can you use Luau in plugins?

1 Like

Sorry for the late response, yes. You can ONLY use Luau for plugins in fact.

Btw I bumped this because, I still am not sure what self is useful to?? I don’t see examples of anyone really using it. Can someone give some examples?