What is "self"?

I’ve had this question for a while, what is self, how do I use it and what is it used for? If you have no idea what I am talking about, take a look at this code sample I found in the dev forum below.

function Appliance:PerformAction()
	coroutine.resume(coroutine.create(function()
		while true do
			wait(self.ActionTimer) -- self.ActionTimer varies depending on the frequency of an object.
			print("I'm a potato")
		end
	end))
end
2 Likes

It’s often used in relation to OOP (or Object Oriented Programming) which is a style of writing code in a more modular/adaptable setting.

There’s some good existing tutorials about Lua and OOP that explain use cases for self. (Link)

1 Like

If so, this is going to be very useful since I am trying to make my games/code as modular as possible.

1 Like

self is a variable that references the table that it was called from.

So

local foo = {}
foo.yes = "Yes"
function foo:frobaculate()
    print(self.yes)
end
foo:fromaculate()

Is the same as

local foo = {}
foo.yes = "Yes"
local function frobaculate(self)
    print(self.yes)
end

fromaculate(foo)
5 Likes

https://www.lua.org/pil/16.html

2 Likes

I’ll experiment with this for a while to get used to it, thanks for the explanation!

1 Like