Is it possible for a loop to break despite checking with “if then”

Hello! I’m making a new game that involves rounds and it’s all run by a single “MainGame” script that starts and continues the game as a loop.

I’ve seen on some of my past games that loops can break, for example, when someone leaves while script is tinkering with them. (Tried to associate nil with player or something like that.) I tried to use functions to make sure it doesn’t just break with the smallest error but there are still some parts that do stuff like [get all players and give them this UI]. I made sure that it checks if the players exists before giving them the UI but my question is;

Is it still possible for it to break even if I checked that the player did exist?

[if player then] → [Give player UI] → [end]

Could someone quit right at the [Give player UI] part and break the loop? Even if it doesn’t have any waits.

If that’s possible, I’ll have to convert everything into a separate function and the loop just calls on them. (Any info is appreciated, I’m still not great at healthy/efficient scripting)

Pcall the entire code that runs within the game loop, if it errors show it as a warning. This should be enough for weird edge cases that have a low possibility of happening. However if you notice any more frequent errors you should add code that handles them instead of ignoring them with a pcall.

Also yes an example were that piece of code might break is if it can’t find the UI or another UI-related error occurs.

1 Like

Thanks for the tip, may I ask how exactly pcall works? Does it ignore the errors instead of breaking the loop when one occurs? Is it enough if I just put the loop in it?

It ignores the error instead of breaking the code, and since this is in a loop when the error occurs it should skip the current loop iteration and restart the round.

Most servers use the same practice as well. That’s how when an error happens on their side you receive a 5xx status error(internal server error) instead of the whole server shutting down.

1 Like

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