I am working on a game and one thing that I want to be able to do is restart my script from another script in case the game script breaks. The script that I want to restart has a while true do loop. If there is a function to restart the script or restart the while true do loop, that would be very helpful.
local scr = game.Workspace.Script scr.Disabled = true scr.Disabled = false
I agree @Meltdown81 but his script may increase lag because it is running at infinite instances.
Clearly, scripts work from top to bottom. If an error arises in any point of the script, the rest of the script that lies below the error will not execute. We can add the Archivable property to our advantage by placing it at the bottom and by using that, we can decide if the script is being executed or not. I would suggest adding this at the bottom of the original script you want to restart:
script.Archivable = false
If the original script is not executing that piece of code, then this new script will fix the rest of the problem:
a = script.Parent.SCRIPTNAME if a.Archivable ~= false then a.Disabled = true wait(0.01) a.Disabled = false end
Let me know if this fixes the problem.
You can do it this way so it doesn't need another script. I use recursion and pcall for checking the crash.
Or you can also do what Meltdown81 mentioned but in the same script.
print("This message only shows if the script is restarted.") local function Crashed() while wait(1) do print("Oops crashed?") print(nil.."Crash") end end -- Recursion local function SafeGuard(anotherFunction) local success,message = pcall(anotherFunction) print("Success? " .. tostring(success).. " : " .. tostring(message)) if success then -- Will never print because of while loop print("Hooray, nothing crashed") else -- You can also do what Meltdown81 mentioned but in the same script. -- Weirdly enough, it works. --script.Disabled = true --script.Disabled = false print("Yeah, it crashed. Restarting the while loop.") SafeGuard(anotherFunction) end end SafeGuard(Crashed)
Instead of restarting the script just restart the contents of the script. What you can do is use remote events the determine when the game script breaks and broadcast a call to the script you want to restart to run the previous code over again. if you trying to do this server to server or client to client then look at the Wiki for some info on doing that but otherwise a simple and clean way to do it would be through remote events