Loops in classes? Object-Oriented Programming

So I decided to have some testing with the OOP system and walked around on something, Loops, I am not sure if I am supposed to be using loops in classes because when I run the class, the loop is way slower, I dont know why.

My question is:
Is it correct to have loops inside classes?
If yes, then why is the loop running slower (I used “wait()” but it looks like it runs 2x slower than that)

1 Like

Wdym loops in classes? Loop on what? Is that a while true do loop since you’re using wait? (ew)
Is that a loop in a table? Your wording is very vague and doesn’t really make sense here?

local mobmodule = require(script.Parent["MobList/Settings"])

local mobclass = {}
mobclass.__index = mobclass

function mobclass.new(mobname,model)
	if mobmodule.MOBS[mobname] then
		local mobmodulefound = mobmodule.MOBS[mobname]
		
		local mob = {model == nil and game.ServerStorage.MOBS[mobmodulefound.ModelName]:Clone() or model}
		setmetatable(mob,mobclass)
		return mob
	else
		return nil
	end
end

function mobclass:Activate(radius)
	local nearestdistance = radius
	local nearestplayer = nil
	while true do
		nearestplayer = nil
		nearestdistance = radius
		for i, v in pairs(game.Players:GetChildren()) do
			if v.Character then
				local distance = v:DistanceFromCharacter(self[1].HumanoidRootPart.Position)
				if distance <= nearestdistance and distance <= radius then
					nearestplayer = v
				end
			end
		end
		if nearestplayer ~= nil then
			print(nearestplayer.Name)
		end
		wait()
	end
end

return mobclass

That is the code

And yea, my speech isn’t a good one, including through speaking and writing

This is an expensive loop, it’s a loop that gets a copy of the players and then loops over it, and has a lot of indexing inside it, and what I would guess are some expensive functions.

First thing I would do here is use RunService instead of while true do with a wait on it, and then also if it doesn’t matter, not update it every time, but just maybe every 0.2 seconds, 0.5 seconds, etc, that’s on you.
I have some info about a lot of what your code has issues with actually, I suggest reading this;

Also I would have personally used .Magnitude instead of this :DistanceFromCharacter function, seems like they’re the same except I’ve never seen that method before.
(Don’t use .magnitude use .Magnitude, the other one is deprecated)

But no, this doesn’t have anything with you using OOP for this.