Invalid argument #1 to 'ipairs' (table expected, got nil)

Working on an OOP module for my game that is supposed to replace .Touched but it brings up this error?

ReplicatedStorage.Modules.Classes.Hitbox:41: invalid argument #1 to 'ipairs' (table expected, got nil)

local Hitbox = {}
Hitbox.__index = Hitbox

function Hitbox.new()
	local self = setmetatable({}, Hitbox)
	self.hit = Instance.new("BindableEvent")
	self._connections = {}
	
	return self
end

function Hitbox:startQuerying(parts)
	for index, part in ipairs(parts) do
		if table.find(self._connections, index) then
			continue
		end
		
		table.insert(self._connections, RunService.PreSimulation:Connect(function(deltaTimeSim)
			local partBoundsInBox = Workspace:GetPartBoundsInBox(part.CFrame, part.Size, overlapParams)
			
			for index, part in ipairs(partBoundsInBox) do
				if not part:HasTag("Ball") then
					continue
				end
				
				self.hit:Fire(part)
				
				Hitbox:disconnectAllConnections()
			end
		end))
	end
end

function Hitbox:disconnectAllConnections()
	for index, connection in ipairs(self._connections) do
		connection:Disconnect()
		
		table.remove(self._connections, index)
	end
	
	table.clear(self._connections)
end

function Hitbox:destroy()
	self:disconnectAllConnections()
	self = nil
end

return Hitbox

Im NOT counting the lines :skull: :skull:

Can you tell me which of the functions/loops does it error?

function Hitbox:disconnectAllConnections()
	for index, connection in ipairs(self._connections) do
		connection:Disconnect()
		
		table.remove(self._connections, index)
	end
	
	table.clear(self._connections)
end

this function, in the ipairs loop, in this function if I print self._connections, it says “nil” but I don’t know why

1 Like

It might be something overriding the table during one of the functions, or a race condition, or it might not be initialising properly, try putting this at the beginning of your disconnectAllConnections() function and see what it prints:

 if type(self._connections) ~= "table" then
        warn("self._connections is not a table. It is:", type(self._connections))
        return
    end
1 Like

Are you calling this method :disconnectAllConnections() in another script? if you call this method like a function the self its gonna be nil:

local hitbox = hitbox.new()
hitbox.disconnectAllConnections() -- self its gonna be nil
1 Like

Im so stupid, I was calling Hitbox:disconnectAllConnections() instead of self… sorry

Fix:
self:DisconnectAllConnections()

1 Like

That is so normal than you think! :joy:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.