How to prevent script execution time error?

I am currently working on a mining game, and when the mine is being created it clones a block and positions it depending on the variables in the code. Everything runs perfectly fine, and I have a Stepped:wait() for every layer that is made. Even though it has this yeild, it still manages to timeout breaking the whole game.

Is there any way I can prevent this? I know other mining games dont have this issue so I know this is possible somehow.

My Script:

--Set Y
	for y = 1,HeightSize do
		--Set Z
		for z = 1,RowSize*2 do
			--Set X
			for x = 1,RowSize*2 do
				local Block = Blocks.Dirt
				--Block Type
				if Ypos == YConstraint then
					Block = Blocks.Dirt
				else --Underground
					local PossibleBlocks = {}
					for _,BlockValue in ipairs(BlockChances) do
						if Ypos <= YConstraint*BlockValue.Depth then
							for count = 1,BlockValue.Chance do
								table.insert(PossibleBlocks,BlockValue)
							end
						end
					end
					
					Block = PossibleBlocks[math.random(1,#PossibleBlocks)].BlockType
					
				end
				--Place Block
				local NewBlock = Block:Clone()
				NewBlock.Position = Vector3.new(Xpos,Ypos,Zpos)
				NewBlock.Parent = Mine
				Xpos += BlockSize
			end
			Xpos = -XConstraint
			Zpos += BlockSize
		end
		Zpos = -XConstraint
		Ypos -= BlockSize
		RunService.Stepped:wait()
	end

Yes, there is:

pcall(function()
    -- put the code that keeps stopping execution in here
end)

So, you could do something like (for example):

while true do
    pcall(function ()
        -- some code here which works sometimes, but when it doesn't work, it stops the while loop. But, by wrapping it in a pcall, the error will be ignored, hence the while loop will continue working
    end)
end

More info needed? Check this out!

2 Likes

How many blocks are you sorting through? If its around a few thousand then its likely caused by having no yield between each section. Essentially what you’re doing is the same as running a while loop with no yields for a short period of time. It causes the execution to hang and as a result it’ll crash.

To fix this execution hang try adding the :Wait() after the first if statement. The only downside to this is that it’ll take a substantial amount of time to go through all the blocks.

@ABHI1290 Your solution is bad practice. Wrapping erroneous code in pcalls because you dont know how to fix the error is never a valid solution and should never be used. pcalls are meant for things like asynchronous functions or promises in which your code relies on a response from an external source you cant guarantee the response from.

1 Like