Why do I get the error unkown global 'self' when it is already defined

I continue to get the error of unknown global ‘self’ and I don’t understand why since it is already defined. This error is occurring in the Upgrader.Init() function. I was doing a little bit of research on it, but the error others were getting was not the same as what I was looking for. Wanted to see if anyone knows why it says its unknown.

local Upgrader = {}
Upgrader.__index = Upgrader

function Upgrader.new(tycoon, instance)
	local self = setmetatable({}, Upgrader)
	self.Instance = instance
	
	return self
end

function Upgrader.Init()
	self.Instance.Detector.Touched:Connect(function(...)
		self:OnTouch(...)
	end)
end

function Upgrader:OnTouch(hit)
	local worth = hit:GetAttribute("Worth")
	
	if worth then
		hit:SetAttribute("Worth", worth * self.Instance:GetAttribute("Multiplier"))
	end
end

return Upgrader

The Error
error4

Not sure what I am missing, but thank you to anyone who is willing to help!

You have it set as a local variable in the function, so you can only use it in that function.

Self doesnt exist there.

function Upgrader:Init()
	self.Instance.Detector.Touched:Connect(function(...)
		self:OnTouch(...)
	end)
end

Maybe try this.

1 Like

when u do “.” functions self wont exist

switch it to :

2 Likes

I’ve been doing that in all my other codes as well though and they all work perfectly fine. It’s just this one that does not.

That’s it. Missed that syntax error. I’ve done that for all my other scripts and wow did I miss that. Thanks, spent a while looking for something like that.

2 Likes