For i,v in pairs() do Is causing my game to freeze / lag out

My game is a rarity game
Like Eternal Rarities or something like that
Anyways it works fine but when i roll a rarity it freezes for a second and i think its cause of my rarity table having like 3000 rarities (auto generated rarities)

This is the part of the script that is lagging the game

local function applyMultiplierToRarities(rarities, multiplier)
	local adjustedRarities = {}
	for _, rarity in ipairs(rarities) do
		if EternityNum.meeq(EternityNum.mul(rarity.chance, multiplier), 1) then
		else
			local rarnum = rarity.number
			local rarname = rarity.name
			table.insert(adjustedRarities, { name = rarname, number = rarnum, chance = EternityNum.div(rarity.chance, multiplier) })
			
		end
	end

	return adjustedRarities
end

I tried adding a “wait()” command but then it just stopped working :sob:

When does this script occur? Everytime a rarity is rolled?

If you can, try to load these over time, using a coroutine and a wait function. If you cannot afford to have this process done over a longer period of time for the code, then you’d have to cut down on the amount of rarities.

I would first profile everything in the loop, especially the EternityNum.meeq function, using the debug library to see which part of it has the biggest footprint.

1 Like

An easy fix for removing lag from expensive loops is setting thresholds of yielding like this:

local threshold = 100 --yield once every 100 loops

for i, v in pairs(t) do
	--code here
	if i%threshold == 0 then task.wait() end
end

Although the real question here is why this function is laggy, as @Prototrode mentioned I suggest you investigate which function has the biggest impact on lag since this may be attributed to one of them(for example meeq, mul or div) which we have no access to in order to help optimize them. I assume what is going on is that one of those functions has a big O(n) complexity which only causes an impact as the rarity table size is increased.

Perhaps you could show us the source code of meeq, mul and div?

Is it entirely necessary to iterate the entire table of rarities when you roll out a rarity? Does rolling out a rarity require you to adjust all the other rarities? If so you could maybe achieve this with a moveable percentage and multiply all the existing rarities with the result from a single calculation of the new rarity. In effect keeping an organic (all encompassing) and constantly shifting multiplier that you apply to each rarity as and when it is needed. The value of the rarities will stay the same but the multiplier will determine their value and rarity in real-time. This will be more realistically achieved if you also decide to choose a base value multiplier to each rarity that can offset the change in value of any other rarities when coupled with the organic (all encompassing) multiplier.